我正在关注这个,控制器首先在下面,测试在下面。启用安全性后,它会显示默认登录页面并且测试失败。是否有一种简单的方法可以仅在测试中绕过安全性?(如果我只是从浏览器运行该应用程序,请获取它按预期工作的测试 url。)
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Data
@Controller
public class HomeController {
@RequestMapping("/home")
public @ResponseBody String greeting(){
return("Hello, World");
}
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/home",
String.class)).contains("Hello, World");
}
}