Spring Boot Test MockMvc执行发布-不起作用

Pab*_*uza 4 testing post spring spring-mvc spring-boot

我正在尝试使用Spring Boot进行集成测试,但是发布请求不起作用。永远不会调用方法saveClientePessoaFisica,并且不会返回任何错误!我只是尝试使用get方法进行其他测试,它可以正常工作。

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class ClienteControllerIT {

    @Autowired
    private MockMvc mvc;


    @Test
    public void nao_deve_permitir_salvar_cliente_pf_com_nome_cpf_duplicado() throws Exception {

        this.mvc.perform(post("/api/cliente/pessoafisica/post")
                .contentType(MediaType.APPLICATION_JSON)
                .content("teste")
                .andExpect(status().is2xxSuccessful());
    }

}

@RestController
@RequestMapping(path = "/api/cliente")
public class ClienteController {

    @Autowired
    private PessoaFisicaService pessoaFisicaService;


    @PostMapping(path = "/pessoafisica/post", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> saveClientePessoaFisica(@RequestBody PessoaFisica pessoaFisica) throws Exception {

        this.pessoaFisicaService.save(pessoaFisica);

        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

}
Run Code Online (Sandbox Code Playgroud)

dde*_*ele 5

要寻找的一些东西:

  • 启用登录您的mockmvc
  • 正确启用您的mockmvc
  • 使用Spring Security时,请在嘲笑mvcvc中对其进行初始化
  • 当使用spring security / CSRF / HTTP POST时,在您的mockmvc中传递一个csrf
  • 启用调试日志记录

像这样 :

logging:
  level:
    org.springframework.web: DEBUG
    org.springframework.security: DEBUG
Run Code Online (Sandbox Code Playgroud)

工作测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@AutoConfigureMockMvc
public class MockMvcTest {

    @Autowired
    protected ObjectMapper objectMapper;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void init() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();

    }

    @Test
    public void adminCanCreateOrganization() throws Exception {

        this.mockMvc.perform(post("/organizations")
                .with(user("admin1").roles("ADMIN"))
                .with(csrf())
                .contentType(APPLICATION_JSON)
                .content(organizationPayload("org1"))
                .accept(APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isCreated());

    }

}
Run Code Online (Sandbox Code Playgroud)

  • 自动装配的 mvcMock 在 init 方法中被替换。此外,如果您需要使用简单的用户和角色,最好使用 `@WithMockUser(username = "admin1", roles = "ADMIN")` 注释测试函数。 (2认同)

Ral*_*ert 5

您的内容“ teste”不是有效的JSON。当我使用您的代码时,我收到一个JsonParseException抱怨(顺便说一句,在content(“ teste”)之后缺少括号)。同样有用的是使用andDo(print()),它将为您提供更详细的请求和响应:

@Test
public void nao_deve_permitir_salvar_cliente_pf_com_nome_cpf_duplicado() throws Exception {

    this.mvc.perform(post("/api/cliente/pessoafisica/post")
            .contentType(MediaType.APPLICATION_JSON)
            .content("teste"))
            .andDo(print())
            .andExpect(status().is2xxSuccessful());
}
Run Code Online (Sandbox Code Playgroud)