主班
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;
}
}
实用类
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 方法调用,但不起作用。任何人都可以帮我解决方案吗?我在我们的应用程序中遇到了类似的功能。
问题是你的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
class:
BootSample bootSample = new BootSample(testUtil);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)