简体   繁体   中英

Test the Spring Boot Rest API Post Method

I completely new to Junit and I have to write Junit Test case for my Rest Controller but I am not getting from where should I start. Any help would be really appreciated.

This is My Rest Controller class.

@RestController
public class RecognitionController {

    private FrameDecoder frameDecoder;
    private TagEncoder tagEncoder;
    private RecognitionService recognitionService;

    @Autowired
    public RecognitionController(FrameDecoder frameDecoder, TagEncoder tagEncoder,
        RecognitionService recognitionService) {

        this.frameDecoder = frameDecoder;
        this.tagEncoder = tagEncoder;
        this.recognitionService = recognitionService;
    }

    /**
     * 
     * @param take the input as Json Frame and map the output at api/detection Url.
     * @return List of Json tag in the Http response.
     */
    @RequestMapping(value = "/api/detection", method = RequestMethod.POST)
    public List<JsonTag> analyseframe(@RequestBody JsonFrame frame) {
        SimpleFrame simpleFrame = frameDecoder.decodeFrame(frame);
        List<OrientedTag> orientedTags = recognitionService.analyseFrame(simpleFrame);
        return tagEncoder.encodeTag(orientedTags);
    }
}

For testing Rest Controller you need:

  1. JUnit
  2. Mockito
  3. Spring Test
  4. JsonPath

Controller:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/Entity")
public class EntityRestController {

    private EntityService service;

    @RequestMapping(value = "/entity/all", method = RequestMethod.GET)
    public List<Entity> findAll() {
        List<Entity> models = service.findAll();
        return createEntities(models);
    }

    private List<EntityDTO> createDTOs(List<Entity> models) {
        List<EntityDTO> dtos = new ArrayList<>();

        for (Entitymodel: models) {
            dtos.add(createDTO(model));
        }

        return dtos;
    }

    private EntityDTO createDTO(Entity model) {
        EntityDTO dto = new EntityDTO();

        dto.setId(model.getId());
        dto.setDescription(model.getDescription());
        dto.setTitle(model.getTitle());

        return dto;
    }
}

Test example:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Arrays;

import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class, WebAppContext.class})
@WebAppConfiguration
public class EntityRestControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private EntityService entityServiceMock;

    //Add WebApplicationContext field here.

    //The setUp() method is omitted.

    @Test
    public void findAllEntitiesTest() throws Exception {
        Entity first = new Entity();
        first.setId(1L);
        first.setDescription("Lorem ipsum")
        first.setTitle("Foo");

        Entity second = new Entity();
        second.setId(2L);
        second.setDescription("Lorem ipsum")
        second.setTitle("Bar");

        when(entityServiceMock.findAll()).thenReturn(Arrays.asList(first, second));

        mockMvc.perform(get("/entity/all"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].id", is(1)))
                .andExpect(jsonPath("$[0].description", is("Lorem ipsum")))
                .andExpect(jsonPath("$[0].title", is("Foo")))
                .andExpect(jsonPath("$[1].id", is(2)))
                .andExpect(jsonPath("$[1].description", is("Lorem ipsum")))
                .andExpect(jsonPath("$[1].title", is("Bar")));

        verify(entityServiceMock, times(1)).findAll();
        verifyNoMoreInteractions(entityServiceMock);
    }
}

Please follow the full tutorial for more details.

___EDIT_1___

I didn't understand from where "thenReturn" Method came

static method Mockito.when() has the following signature:

public static <T> OngoingStubbing<T> when(T methodCall) 

When you mocking some service and putting it inside when as parameter - it returns object which IS OngoingStubbing<T> . All classes which implement OngoingStubbing<T> have thenReturn(T value) method and it's called.

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