主要类
public class BootSample {
public int call(int m) {
System.out.println("Entering into Call Method");
int n = m*10;
TestUtil testUtil = new TestUtil();
testUtil.add(m, n);
System.out.println("End of Call Method Value n : " + n);
return n;
}
}
Util类
public class TestUtil {
public void add(int a, int b) {
System.out.println(" Entering into TestUtil Method ");
int c = a +b;
System.out.println(" End of TestUtil Method Value : " + c);
}
}
测试类
@RunWith(MockitoJUnitRunner.class)
public class BootSampleTest {
@Mock
TestUtil testUtil;
@Before
public void setup() {
}
@Test
public void utilSuccess() throws Exception {
BootSample bootSample = new BootSample();
doNothing().when(testUtil).add(any(Integer.class),any(Integer.class));
int result = bootSample.call(10);
assertEquals(result,100);
}
}
输出:
Entering into Call Method
Entering into TestUtil Method
End of TestUtil Method Value : 110
End of Call Method Value n : 100
我正在尝试使用doNothing来模拟util void方法调用但不起作用。任何人都可以帮我解决一下吗?我在应用程序中遇到了类似的功能。
答案 0 :(得分:2)
问题是您的call
方法负责创建TestUtil
对象,并且该对象无法被模拟。尝试添加TestUtil作为构造函数参数,如下所示:
public class BootSample {
private TestUtil testUtil;
public BootSample(TestUtil testUtil) {
this.testUtil = testUtil;
}
public int call(int m) {
System.out.println("Entering into Call Method");
int n = m*10;
testUtil.add(m, n);
System.out.println("End of Call Method Value n : " + n);
return n;
}
}
然后你需要模拟TestUtil
类并将模拟传递给BootSample
类:
BootSample bootSample = new BootSample(testUtil);
答案 1 :(得分:1)
如果您从TestUtil类中看到System.out.printlns,则不会嘲笑它。看起来你错过了BootSample上的@InjectMocks,告诉Mockito将你的模拟TestUtil注入其中。
请参阅此处文档中的示例:http://static.javadoc.io/org.mockito/mockito-core/2.13.0/org/mockito/InjectMocks.html
答案 2 :(得分:1)
您可以使用Mockito.anyInt()
代替Integer.class
,
代码示例:
Mockito.doNothing().when(testUtil).add(Mockito.anyInt(),Mockito.anyInt());