Mockito mock現在のクラス【同一クラス】でのメソッド
1650 ワード
この問題は長い間悩んでいたので、リンクをクリックすることを参考にしてください.
直接コード:はmockクラス によって
2.Testクラス
主にこのコードが役立ちます.
メソッドの戻り値を与え,呼び出された杭打ちクラスが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メソッドに対応すると,思いがけない結果が得られる.
このブロガーの共有に感謝します