代码之家  ›  专栏  ›  技术社区  ›  Mitch

Mockito-测试返回类型是否与预期相同

  •  1
  • Mitch  · 技术社区  · 7 年前

    我非常沮丧,因为我无法理解这一点。我读了很多文章,但我不知道如何解决这个问题,但我认为我忽略了一些非常简单的东西。

    我有一个有几个端点的类,其中一个是:

    @GET
    @Path("courses")
    @Produces(MediaType.APPLICATION_JSON)
    public Response courses(@QueryParam("token") String token) {
        Integer studentId = iStudentDAO.getStudentIdByToken(token);
        if(studentId == null){
            return Response.status(403).build();
        } else {
            GetStudentsResponse studentCourses = iStudentDAO.getStudentCourses(studentId);
            return Response.status(200).entity(courses.name).build();
        }
    }
    

    此方法应始终返回响应。地位这正是我想要测试的。我知道不可能对实际响应(200或403)进行单元测试,但我想知道如何测试至少是否有响应。返回状态。我在我的Maven项目中使用Mockito来实现这一点。

    @Test   
    public void testGetAllCourses () {
       String token = "100-200-300";
       StudentRequests studentRequests = mock(StudentRequests.class);        
       when(studentRequests.courses(token)).thenReturn(Response.class);
       Response expected = Response.class;
       assertEquals(expected, studentRequests.courses());
    }
    

    有人能告诉我如何做到这一点吗?:)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Yogesh_D    7 年前

    你应该能够测试你的具体反应。 假设,方法 courses 正在上课 Controller 。这是您正在测试的类,您的目标应该是在这里测试代码,这是您在控制器中编写的代码。 以下是一个示例:

    package test;
    
    import static org.junit.Assert.*;
    
    import org.apache.catalina.connector.Response;
    import org.junit.Before;
    import org.junit.Test;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.mockito.MockitoAnnotations;
    
    public class ControllerTest {
    
        @Mock
        IStudentDAO iStudentDAO;
    
        @InjectMocks
        Controller controller;
    
        @Before
        public void init() {
            MockitoAnnotations.initMocks(this);
        }
    
        @Test
        public void testCoursesWhenStudentIDNotFound() {
            Mockito.when(iStudentDAO.getStudentIdByToken("1234")).thenReturn(null);
            Response response = controller.courses("1234");
            assertEquals(403, response.getStatus())
        }
    
    }
    

    类似地,在下一个测试用例中,您可以模拟 IStudentDAO ,以返回 studentId 然后是这方面的课程 学生ID 并验证您是否在响应中得到了他们。

    推荐文章