使用Junit和Mock put请求进行测试

时间:2020-06-14 23:08:59

标签: java spring-boot junit mockito

我正在尝试对put请求进行测试,仅在这种类型的请求中它给了我空指针错误,我不知道为什么有人可以帮助我,这是我的控制器:

0                            
1    jumped over the lazy dog
2    jumped over the lazy dog
Name: text, dtype: object

以及测试方法:

@PutMapping ("/update/{id}")
    public Entreprise updateEntreprise(@PathVariable Long id,@RequestBody Entreprise entreprise ) {
       Entreprise e=entrepriseService.getEntreprise(id);
       e.setDescription(entreprise.getDescription());
       e.setNom(entreprise.getNom());
       e.setNumberCertificats(entreprise.getNumberCertificats());
       e.setNumberClients(entreprise.getNumberClients());
       e.setNumberYears(entreprise.getNumberYears());
       e.setNumberCollaborators(entreprise.getNumberCollaborators());
       entrepriseService.updateEntreprise(e);
        return e;
    }

2 个答案:

答案 0 :(得分:0)

我没有看到您嘲笑服务电话。 添加-Mockito.when(entrepriseService.getEntreprise(Mockito.anyLong()))。thenReturn(new Entreprise())

答案 1 :(得分:0)

您需要模拟来自entrepriseService的两个呼叫

  1. 用于getEntreprise(id)
  2. 对于updateEntreprise(e)

尝试在以下代码下运行

@RunWith(SpringRunner.class)
@WebMvcTest(value = EntrepriseController.class, secure = false)
public class TestsEntrepriseController {
    @Autowired
    private MockMvc mockMvc;


    @MockBean
    EntrepriseService entrepriseService;
 @Test
    public void givenEntrepriseURIWithPut_whenMockMVC_thenVerifyResponse() throws Exception {
        Entreprise entreprise = new Entreprise();
        entreprise.setId(1);
        entreprise.setNom("oumaima");
        entreprise.setDescription("description");
        entreprise.setNumberCertificats(12);
        entreprise.setNumberClients(15);
        entreprise.setNumberCollaborators(20);
        entreprise.setNumberYears(12);
        Services services = new Services();
        services.setNom("cloud");
        services.setId(1);
        Set<Services> allServices =  new HashSet<>(Arrays. asList(services));
        entreprise.setServices(allServices);

        Mockito.when(entrepriseService.getEntreprise(Mockito.any())).thenReturn(new Entreprise());
        Mockito.when(entrepriseService.updateEntreprise(Mockito.any(Entreprise .class))).thenReturn(entreprise);

        mockMvc.perform(put("/entreprise/update/1")
                .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8)
                .content(IntegrationTestUtil.convertObjectToJsonBytes(entreprise))
        )
                .andExpect(status().isBadRequest())
                .andExpect(content().string("{\"fieldErrors\":[{\"path\":\"title\",\"message\":\"The title cannot be empty.\"}]}"));

    }
}