首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试方法

测试方法
EN

Stack Overflow用户
提问于 2017-06-01 13:26:58
回答 1查看 4.8K关注 0票数 1

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

这是我的Rest控制器类。

代码语言:javascript
复制
@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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-06-01 13:36:26

为了测试Rest控制器,您需要:

  1. JUnit
  2. 莫基托
  3. 弹簧试验
  4. JsonPath

主计长:

代码语言:javascript
复制
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;
    }
}

测试示例:

代码语言:javascript
复制
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);
    }
}

请跟随全教程了解更多细节。

___EDIT_1___

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

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

代码语言:javascript
复制
public static <T> OngoingStubbing<T> when(T methodCall) 

当您模拟某个服务并将其作为参数放在when中时,它返回对象,即OngoingStubbing<T>。实现OngoingStubbing<T>的所有类都有thenReturn(T value)方法,它被调用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44308844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档