简单的 Mokito 示例
Simple Mokito example
您好,我一直在为 Mokito 苦苦挣扎,在对堆栈溢出和其他资源进行一些搜索后,我仍然无法得到它。
假设我有一个 class B 看起来像这样:
public class B {
private String name;
public String getName(){
return this.name;
}
public void test(){
String name = getName();
if (name.equals("S")){
methodToCall();
}
}
public void methodToCall(){};
}
我的目标是测试 methodToCall
是否在名称等于“S”时被调用,否则不被调用。
我试过的是写另一个 class A ,它有一个方法来获取 class B 的实例,如下所示:
public class A {
public void publish(B classb){
classb.test();
}
}
然后我有一个测试 class 定义如下:
public class Test {
public static void main(String[] args) {
A a = new A();
B classb = mock(B.class);
when(classb.getName()).thenReturn("S");
a.publish(classb);
verify(classb, times(1)).methodToCall();
}
}
我的理解是当mock对象遇到方法getName
时,它会return我在when
方法中输入的字符串“S”,然后它应该进入if 语句并执行这个 methodToCall
,但是 IDE 给了我这个错误:
Exception in thread "main" Wanted but not invoked:
b.methodToCall();
-> at Test.main(Test.java:12)
However, there were other interactions with this mock:
b.test();
-> at A.publish(A.java:3)
at Test.main(Test.java:12)
我真的很想了解这里发生了什么,如果有任何帮助,我将不胜感激。
我知道我在这里有一定程度的误解,但如果有人能告诉我这个错误信息到底是什么意思,为什么会出现在第一位以及如何解决它,我将不胜感激。
(请注意,我对注释还不太满意,所以一切都以原始方式完成)
当你嘲笑 class B 时,你嘲笑了它的全部。这意味着你从来没有真正 运行 “测试”函数,而是 运行 一个什么都不做的模拟测试函数,因为当你 运行 这个时你没有告诉模拟该做什么函数...
如果你想让 mock 通过调用 when(classb.test()).thenCallRealMethod();
来执行真正的方法,但我不推荐这样做。相反,我建议您阅读以下 this question 关于何时使用 mockito 并问问自己 class 您想要测试什么。
根据经验,我只想说,如果你想在 class B 中测试方法,你不应该模拟 class B。Mockito 应该模拟 class依赖项可帮助您仅专注于测试目标 class (unitest),而不依赖于其他 classes 的行为方式。
您好,我一直在为 Mokito 苦苦挣扎,在对堆栈溢出和其他资源进行一些搜索后,我仍然无法得到它。 假设我有一个 class B 看起来像这样:
public class B {
private String name;
public String getName(){
return this.name;
}
public void test(){
String name = getName();
if (name.equals("S")){
methodToCall();
}
}
public void methodToCall(){};
}
我的目标是测试 methodToCall
是否在名称等于“S”时被调用,否则不被调用。
我试过的是写另一个 class A ,它有一个方法来获取 class B 的实例,如下所示:
public class A {
public void publish(B classb){
classb.test();
}
}
然后我有一个测试 class 定义如下:
public class Test {
public static void main(String[] args) {
A a = new A();
B classb = mock(B.class);
when(classb.getName()).thenReturn("S");
a.publish(classb);
verify(classb, times(1)).methodToCall();
}
}
我的理解是当mock对象遇到方法getName
时,它会return我在when
方法中输入的字符串“S”,然后它应该进入if 语句并执行这个 methodToCall
,但是 IDE 给了我这个错误:
Exception in thread "main" Wanted but not invoked:
b.methodToCall();
-> at Test.main(Test.java:12)
However, there were other interactions with this mock:
b.test();
-> at A.publish(A.java:3)
at Test.main(Test.java:12)
我真的很想了解这里发生了什么,如果有任何帮助,我将不胜感激。 我知道我在这里有一定程度的误解,但如果有人能告诉我这个错误信息到底是什么意思,为什么会出现在第一位以及如何解决它,我将不胜感激。 (请注意,我对注释还不太满意,所以一切都以原始方式完成)
当你嘲笑 class B 时,你嘲笑了它的全部。这意味着你从来没有真正 运行 “测试”函数,而是 运行 一个什么都不做的模拟测试函数,因为当你 运行 这个时你没有告诉模拟该做什么函数...
如果你想让 mock 通过调用 when(classb.test()).thenCallRealMethod();
来执行真正的方法,但我不推荐这样做。相反,我建议您阅读以下 this question 关于何时使用 mockito 并问问自己 class 您想要测试什么。
根据经验,我只想说,如果你想在 class B 中测试方法,你不应该模拟 class B。Mockito 应该模拟 class依赖项可帮助您仅专注于测试目标 class (unitest),而不依赖于其他 classes 的行为方式。