Spring Boot JUnit5 Mokito 时返回不起作用

问题描述 投票:0回答:1

更新

奇怪的是,当我在控制器中设置

String token = ""
而不是
String token = null
时,我的测试就通过了。

Mokito 返回默认值

null
而不是
OK
字符串。所以我的 NPE 测试失败了。

Caused by: java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because "result" is null

我的测试方法:

@Test
    void testPatchTestClusterVM() throws Exception {     

        //Given
        when(clusterService.startPatchingTest(any(), anyString(), anyString(), anyString())).thenReturn("OK");
        
        //When
        RequestBuilder request = MockMvcRequestBuilders
                .post("/patch/clustertest/mycluster/host/vc2crtp1770461np")
                .accept(MediaType.APPLICATION_JSON);
        
        //Then
        mockMvc.perform(request)
                .andExpect(status().isOk())
                .andReturn();       
    }

我的控制器方法:

@PostMapping("/patch/clustertest/{clustername}/host/{hostname}")
    public ResponseEntity<?> patchClusterTestVM(@PathVariable("clustername") String clusterName, @PathVariable("hostname") String hostName) {
        String token = null;
        String uuid = UUID.randomUUID().toString();     
        String result = clusterService.startPatchingTest(new ClusterDetailsClass(1L, "mycluster"), hostName, token, uuid);
        return new ResponseEntity<String>(result.toLowerCase(), HttpStatus.OK);
    }
java spring-boot junit5
1个回答
0
投票

您没有显示所有相关代码,例如测试类注释以及集群服务如何初始化和注入。我认为这应该有效:

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
class ClusterTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ClusterService clusterService;

    @Test
    void testPatchTestClusterVM() throws Exception {     

        //Given
        when(clusterService.startPatchingTest(any(), anyString(), anyString(), anyString())).thenReturn("OK");
        
© www.soinside.com 2019 - 2024. All rights reserved.