2017-04-18 101 views
0

我想使用Spring Boot进行集成测试,但发布请求不起作用。方法saveClientePessoaFisica永远不会被调用,并且不会返回任何类型的错误!我只是尝试使用get方法进行其他测试,并且它正常工作。春季启动测试MockMvc执行后 - 不能正常工作

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

} 

回答

1

你的内容 “阿泰斯特” 没有有效的JSON。当我使用你的代码时,我得到一个JsonParseException的抱怨(顺便说一下,在内容(“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()); 
} 
1

有些事情要寻找:

  • 在mockmvc
  • 使您mockmvc启用日志记录正常
  • 当使用弹簧安全,初始化它mockmvc
  • 当使用弹簧安全/ CSRF/HTTP POST,在您的mockmvc中传递一个csrf
  • 启用调试日志记录

像这样:

logging: 
    level: 
    org.springframework.web: DEBUG 
    org.springframework.security: DEBUG 

工作测试:

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

    } 

} 
+0

非常感谢!这个日志提示非常有用! –

+0

自动装配的mvcMock在init方法中被替换。另外,如果您需要使用简单的用户和角色,可以使用@WithMockUser(username =“admin1”,roles =“ADMIN”)更好地标注测试函数。 – EliuX

+0

非常感谢您提供这个调试提示!非常有用和实用 – kidnan1991