【问题标题】:How to write Junit Test Cases in springBoot?如何在 Spring Boot 中编写 Junit 测试用例?
【发布时间】:2021-07-26 14:47:23
【问题描述】:

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

@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

【问题讨论】:

  • 你在谷歌上没有找到任何东西吗?
  • 如果你能证明你所付出的努力以及为什么它不起作用,你将会取得更大的成功。那么人们会更愿意提供帮助
  • 当然,请检查@batman567,这样好吗

标签: java spring-boot junit mockito junit4


【解决方案1】:

这可能是一个例子:

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

【讨论】:

【解决方案2】:

查看可能有帮助的示例

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

【讨论】:

    【解决方案3】:

    我通常或多或少地像这样编写我的控制器测试。如果你想测试 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 外观,但这些都不是任何令人惊奇的测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      相关资源
      最近更新 更多