如何在 springBoot 中编写 Junit 测试用例?

问题描述

这是我的控制器类的映射,现在我想为它编写单元测试用例

@GetMapping(value = "/tokenSearch/{id}/{name}/{values}/{data_name}",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getValuesfromToken(
        
        throws ClientProtocolException,IOException,ParseException {
    ResponseEntity<String> data = elasticService.getData();
    return data;

}

这就是我正在尝试的,但它要求结果匹配器的castargument,出现错误,有人可以帮助我吗

@RunWith(springrunner.class)
@SpringBoottest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfiguremockmvc
public class ElasticCaseTests extends Mockito {

    @Autowired
    private mockmvc mockmvc;

    @Test
    public void testGetValuesfromToken() throws Exception {
        String contentAsstring = mockmvc.perform(get("/tokenSearch/1/PRODUCT/PRODUCT/189")).andExpect(status().isOk())
                .andExpect(jsonPath("$.id",is("1"))).andExpect(jsonPath("$.name",is("product")))
                .andExpect(jsonPath("$.values",is("product")))
                .andExpect(jsonPath("$.searching_word",is("189"))).andExpect(status().isOk()).andReturn().getResponse()
                .getContentAsstring();
    }

    
java.lang.AssertionError: No value at JSON path "$.id"',can someone help me with this

解决方法

这可能是一个例子:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class ControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
    void testGetValuesfromToken() throws Exception  {
        
        this.mockMvc
        .perform(get("/tokenSearch/............."))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.hierarchy_name"").value(".....what you expect..."))
        .andDo(print());
    }
,

查看可能有帮助的示例

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import ….services.AuthorizationService;
import ….AuthorizationRequest;
import ….AuthorizationResponse;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import org.junit.Before;
import org.junit.Test;

public class MyControllerTest {

    AuthorizationService authorizationService;
    AuthorizationController controller;
    private Clock clock;

   @Before
   public void setUp() throws Exception {
       clock = Clock.fixed(Instant.now(),ZoneId.systemDefault());
       authorizationService = mock(AuthorizationService.class);
       controller = new AuthorizationController(authorizationService);
   }

   @Test
   public void createJws() throws Exception {

      when(authorizationService.createJws(any(AuthorizationRequest.class)))
          .thenReturn(new AuthorizationResponse());
      AuthorizationRequest authorizationRequest =
      AuthorizationRequest.builder().id(“abc”).build();

      AuthorizationResponse jwsResponse = 
      controller.createJws(authorizationRequest);
      verify(authorizationService).createJws(authorizationRequest);
   }
 }
,

我通常或多或少地这样编写我的控制器测试。如果你想测试 json 输出和状态的正确性,你可以实现一个像 asJsonString 这样的辅助方法,看看是否一切正常。也许您觉得这种方法很有帮助。

@WebMvcTest
@ContextConfiguration(classes = {ResourceController.class})
class ResourceControllerTest {

private final String JSON_CONTENT_TYPE = "application/json";

@Autowired
private MockMvc mockMvc;
@MockBean
private ElasticService elasticService;

@Test
public void shouldReturnProperData() throws Exception {
    String data = "some returned data"; // format it properly,as elasticService would
    YourJsonObject objectToReturn = new YourJsonObject(...);
    when(elasticService.getData()).thenReturn(data);

mockMvc.perform(post("/tokenSearch/1/PRODUCT/PRODUCT/189").contentType(JSON_CONTENT_TYPE).content(asJsonString(email)))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(content().string(asJsonString(objectToReturn)));
    }
}

private String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e); // delete this exception conversion if you will :)
    }
}
}

最重要的是测试 elasticService 是否返回正确的数据,以便您可以在那里实施单元测试。在这里,您可以测试状态、路径和 json 外观,但这些都不是什么了不起的测试。