现在有 学生类 Student:
类中有一个方法checkPc(),连接数据库查询该学生是否符合某种条件可以配置电脑。
返回0:不能配置电脑
返回1:可以配置电脑
int checkPc(){
System.out.println("连接数据库查询当前学生"+this.name+"是否符合条件,result");
int flag = 0;
if(1==2){
return flag;
}else {
flag=1;
return flag;
}
}
然后根据返回结果调用 sayHello()方法,执行相关操作。
可以看出,由于sayHello方法很简单,只需要传参 int 类型即可测试,不必非要调用关联方法。
假设场景条件很复杂,现在无法连接数据查询,那么应该如何测试sayHello(int flag)方法。
public String sayHello(int flag){
if(flag==1){
System.out.println("Yes."+this.name+" can have a laptop");
Computer c = new Computer("Mac","MacBook");
return this.name+" have a "+c.getMake()+" "+c.getModel();
}else {
System.out.println("不配置电脑");
return this.name+" cant have a laptop";
}
}
新建测试类:
待测类加Mock注解
@Mock
private Computer c;
在测试方法中初始化:
MockitoAnnotations.initMocks(this);
假设学生类无需mock,直接创建一个学生类:
Student student = new Student("Charlie", 30);
由于 sayHello 方法默认给学生配置电脑,因此可以mock get方法以获取电脑品牌和型号,由于sayHello 方法名默认配置了"Mac"和"MacBook",因此在此处让他返回相同数据:
when(c.getMake()).thenReturn("Mac");
when(c.getModel()).thenReturn("MacBook");
断言:
只有当sayHello(1)时,可以配置电脑并返回学生姓名和电脑名称。其他数据不能配置电脑。
assertEquals(student.getName()+" have a "+c.getMake()+" "+c.getModel(), student.sayHello(1));
assertEquals(student.getName()+" cant have a laptop", student.sayHello(0));
assertEquals(student.getName()+" cant have a laptop", student.sayHello(2));
完整测试类代码:
class StudentTest1029 {
@Mock
private Computer c;
@Test
void sayHello() {
MockitoAnnotations.initMocks(this);
Student student = new Student("Charlie", 30);
when(c.getMake()).thenReturn("Mac");
when(c.getModel()).thenReturn("MacBook");
assertEquals(student.getName()+" have a "+c.getMake()+" "+c.getModel(), student.sayHello(1));
assertEquals(student.getName()+" cant have a laptop", student.sayHello(0));
assertEquals(student.getName()+" cant have a laptop", student.sayHello(2));
}
}
执行结果:
如有错误请指正