单位测试是嘲笑服务方法或直接测试服务方法的测试控制器方法



上下文:春季启动,休息的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
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. 通过模拟服务方法测试控制器方法的测试

哪种正确编写单元测试的方法?

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

相关内容

  • 没有找到相关文章

最新更新