单元测试是测试模拟服务方法的控制器方法还是直接测试服务方法?

时间:2017-06-24 10:25:43

标签: spring web-services rest unit-testing mocking

上下文:Spring Boot,RESTful Web服务。

我为Survey项目编写了一个Web服务,

@RestController
public class SurveyEndpoint {

   @Autowired
   private SurveyService surveyService;

   @RequestMapping(value="surveys/{surveyId}/questions/{questionId}", method=RequestMethod.GET)
   public QuestionEntity getQuestions(@PathVariable String surveyId, @PathVariable String questionId){
            return surveyService.retrieveQuestionById(surveyId, questionId);
}

下面是Component class:

@Component
public class SurveyService {

    public QuestionEntity retrieveQuestionById(String surveyId, String questionId) {

            //Code for retrieving question
        }

我写了一个单元测试,直接测试组件方法如下:

public class SurveyServiceTest {
    @Autowired
    SurveyService surveyService;

    @Test
    public void testRetrieveQuestionById() {

        QuestionEntity questions = surveyService.retrieveQuestionById("Survey1", "Question1");

        assertEquals("Question1", questions.getQuestionId());
    }

其他方式是直接测试控制器方法,如下所示:

@Test
    public void testRetrieveQuestionById() throws Exception {
        QuestionEntity mockQuestion = new QuestionEntity("Question1",
                "Largest Country in the World", "Russia", Arrays.asList(
                        "India", "Russia", "United States", "China"));

        Mockito.when(
                surveyService.retrieveQuestionById(Mockito.anyString(), Mockito.anyString())).thenReturn(mockQuestion);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/surveys/Survey1/questions/Question1").accept(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        String expected = "{id:Question1,description:Largest Country in the World,correctAnswer:Russia}";

        JSONAssert.assertEquals(expected, result.getResponse()
                .getContentAsString(), false);

        // Assert
    }
}

从上面开始,

  1. 直接测试服务方法

  2. 通过模拟服务方法测试控制器方法的测试

  3. 哪种方法可以编写单元测试?

1 个答案:

答案 0 :(得分:0)

这是针对两个不同组件的两个不同的单元测试,因此单元测试没有比另一个好。