我正在为我的控制器编写一个单元测试,它有一个注入的Authentication参数
@RequestMapping(value = Mappings.PEOPLE, method = RequestMethod.POST)
public ResponseEntity<?> people(HttpServletRequest request, Authentication authentication, @RequestBody Person person) {
...
}
我不知道如何在我的测试中设置认证。这是我到目前为止所拥有的。
@RunWith(SpringRunner.class)
public class PeopleTest {
@Before
public void setUp() {
RestAssuredMockMvc.standaloneSetup(new PeopleController());
}
@Test
public void testKanbanOnlyScan() {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("username", "password"));
given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(new Person("Davey Jones"))
.when()
.post("/people")
.then()
.statusCode(is(HttpStatus.OK.value()));
}
}
但在测试期间,我的控制器中的身份验证为空。如何将身份验证注入控制器?
答案 0 :(得分:1)
您可以使用MockMVC来测试控制器,例如:
@Autowired
MockMVC mockMvc;
mockMvc.perform("/your-controller-path").with(authentication(authentication))
有关详细信息,请参阅spring docs
答案 1 :(得分:0)
如果正在使用WebApplicationContext,则仍可以使用RestAssuredMockMvc。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TodoControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
@BeforeEach
void init() {
RestAssuredMockMvc.webAppContextSetup(webApplicationContext);
}
@Test
void secured_api_should_react_with_default(){
given()
.when()
.get("/todo/")
.then()
.statusCode(HttpStatus.UNAUTHORIZED.value());
}
@Test
public void secured_api_should_give_http_200_when_authorized() {
given()
.auth().with(SecurityMockMvcRequestPostProcessors.httpBasic("foo", "bar"))
.when()
.get("/todo/")
.then()
.statusCode(HttpStatus.OK.value());
}
}