【问题标题】:Test the Spring Boot Rest API Post Method测试 Spring Boot Rest API Post 方法
【发布时间】:2017-11-02 16:18:32
【问题描述】:

我对 Junit 完全陌生,我必须为我的 Rest Controller 编写 Junit 测试用例,但我没有从哪里开始。任何帮助将不胜感激。

这是我的 Rest Controller 类。

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

【问题讨论】:

    标签: java rest spring-boot junit


    【解决方案1】:

    为了测试你需要的 Rest Controller:

    1. JUnit
    2. Mockito
    3. 春季测试
    4. JsonPath

    控制器:

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

    测试示例:

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

    更多详情请关注full tutorial

    ___EDIT_1___

    我不明白“thenReturn”方法是从哪里来的

    静态方法Mockito.when()具有以下签名:

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

    当您模拟某些服务并将其作为参数放入 when 时 - 它会返回 IS OngoingStubbing&lt;T&gt; 的对象。所有实现OngoingStubbing&lt;T&gt; 的类都有thenReturn(T value) 方法并被调用。

    【讨论】:

    • 感谢@J-Alex 的回答,但我不明白“thenReturn”方法是从哪里来的,您能否解释一下它对我真的很有帮助。
    猜你喜欢
    • 2023-03-25
    • 2017-04-23
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 2016-02-15
    • 1970-01-01
    • 2019-12-28
    相关资源
    最近更新 更多