这个问题纠结我很久,参考自 点击链接
直接上代码:
- 被mock类
public class Person {
private String name;
private int age; public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean runInGround(String location) {
if(location.equals("ground")) {
System.out.println("The person runs in the " + location);
return true;
} else {
System.out.println("The person doesn't run in the " + location);
return false;
}
}
public boolean isPlay() {
if(this.runInGround("ground")) {
System.out.println("The person plays.");
return true;
}
else {
System.out.println("The person doesn't play");
return false;
}
}
}
2.Test类
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class PersonTest{
@Test
public void playTest() {
Person person = new Person("name", 15, "23435678V");
Person person1 = Mockito.spy(person);
Mockito.doReturn(true).when(person1).runInGround("ground");
Assert.assertEquals(true, person1.isPlay());
}
}
主要起作用的是这句代码:
Mockito.doReturn(true).when(person1).runInGround("ground");
给出方法返回值,调用的打桩类对应mock方法,就有意想不到的结果。
感谢这位博主的分享
本文介绍了如何使用Mockito框架在Java中对同一类的内部方法进行mock,通过具体的代码示例展示了设置mock方法返回值的方法,从而实现对测试类内部行为的控制。
7207

被折叠的 条评论
为什么被折叠?



