码农进阶之旅Android开发Android知识

AndroidStudio测试(四)单元测试Mock以及Mock

2017-02-16  本文已影响155人  泅渡者

网络测试

这篇文章我们模拟一个场景:我们在学校教务软件中要获取学生的信息,获取方式有两种第一种是通过本地数据库获取,第二种是通过网络获取。
为此我们新建一个Student类来描述学生信息如下:

public class Student {
    public int id ;
    public String name;
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

接下来我们建一个接口用来获取学生的信息。

public interface StudentDao {
    Student getStudentFromDB(int sid);
}

但是此时我们不去实现这个接口,因为工作时很多情况都是分工合作,你做的功能需要别人的配合,往往会影响开发效率,那么我们该怎么去测试自己的代码呢,下面我们建立一个StuController类来控制是从何处获取学生信息。

public class StuController {

    private StudentDao studentDao;

    public Student getStudentInfo(int sid){
        Student student = null;
        if(studentDao != null){
            student = studentDao.getStudentFromDB(sid);
        }
        if(student == null){
            student = fetchStudent(sid);
        }
        return student;
    }

    private Student fetchStudent(int sid) {
        System.out.print("模拟网络获取学生信息");
        Student student = new Student();
        student.id = 12;
        student.name = "网络名";
        return student;
    }

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}

以上代码相信大家都能看懂,下面我们建立一个Student测试类

public class StuControllerTest {
    StuController stuController;
    StudentDao studentDao;
    @Before
    public void setUp() throws Exception {
        stuController = new StuController();
        studentDao = mock(StudentDao.class);
        stuController.setStudentDao(studentDao);
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void getStudentInfo() throws Exception {
        Student returnStudent = new Student();
        returnStudent.id = 123;
        returnStudent.name = "Mock-user";

        when(studentDao.getStudentFromDB(anyInt())).thenReturn(returnStudent);

        Student student = stuController.getStudentInfo(123);
        TestCase.assertEquals(123,student.id);
        TestCase.assertEquals("Mock-user",student.name);

        System.out.print(studentDao.getStudentFromDB(1));

    }

    @Test
    public void testGetStudentInfoFromSever(){
        when(studentDao.getStudentFromDB(anyInt())).thenReturn(null);
        Student student = stuController.getStudentInfo(456);
        TestCase.assertEquals(12,student.id);
        TestCase.assertEquals("网络名",student.name);

    }

}

从上面代码可以看到,我们并没有实现StudentDao,我们只是应用Mock 创建了一个studentDao的实例。
上面这个方法是测试数据库获取数据是否成功。

    @Test
   public void getStudentInfo() throws Exception {

而这个方法就是测试网络数据是否获取成功。

 @Test
    public void testGetStudentInfoFromSever(){

以下便是测试结果 image.png

本人不善言辞,但欢迎大家批评与指正。

上一篇下一篇

猜你喜欢

热点阅读