在 RestAssuredMockMvc 中注入身份验证

Injected authentication in RestAssuredMockMvc

我正在为注入了身份验证参数的控制器编写单元测试

 @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()));
    }
}

但在测试期间,我的控制器中的身份验证为空。如何将身份验证注入控制器?

您可以使用 MockMVC 来测试您的控制器,方法如下:

@Autowired
MockMVC mockMvc;
mockMvc.perform("/your-controller-path").with(authentication(authentication))

有关详细信息,请查看 spring 文档

preview-spring-security-test-web-security

如果您使用的是 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());

    }
}