android mock测试,AndroidStudio测试(四)单元测试Mock以及Mockito的使用

络测试

这篇文章我们模拟一个场景:我们在学校教务软件中要获取学生的信息,获取方式有两种第一种是通过本地数据库获取,第二种是通过 络获取。

为此我们新建一个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(){

以下便是测试结果

d61a1e9acc0e

image.png

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

相关资源:电子礼金簿Ver1.5-管理软件其他资源-CSDN文库

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2021年4月22日
下一篇 2021年4月22日

相关推荐