简体   繁体   中英

How to write Junit Test Cases in springBoot?

Thid is my mapping from my controller class, now I want to write unit test case for the same

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

}

this is what I was trying but its asking for castargument for Result matcher, getting error, can someone pls help me with this

@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

This could be one example:

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

See example it may help

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

I usually write my Controller tests more or less like this. If you want to test the json output and status correctness, you could implement a helper method like asJsonString and see if everything is proper. Maybe you find this approach helpful.

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

The most important is though to test if elasticService returns the proper data so you can implement the unit tests there. Here, you can test statuses, paths, and slightly the json outlook, but these are not any kind of amazing tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM