![](/img/trans.png)
[英]Mockito - Interface method is called when I need it to call the implementation class
[英]In Mockito, Is there any way to mock Class (instead of interface) which have method that need to mocked and method that need to be tested?
我试图模拟具有该方法的 class
public double add(double in1, double in2)
和
@Test
public void test()
当我运行代码时,出现错误
**Wanted but not invoked:
calculator.add(10.0, 20.0);
-> at main.Calculator.test(Calculator.java:20)
Actually, there were zero interactions with this mock.**
请找到代码的屏幕截图。
Jul 24, 2020 11:48:05 PM main.TestCalculator main
INFO: test(main.Calculator):
**Wanted but not invoked:
calculator.add(10.0, 20.0);
-> at main.Calculator.test(Calculator.java:20)
Actually, there were zero interactions with this mock.**
Jul 24, 2020 11:48:05 PM main.TestCalculator main
INFO: Result: false
您的verify
语句应该在您正在验证的方法被调用之后出现。 在这种情况下,您尝试验证是否调用了add
方法,但在您的 verify 语句之前未调用该方法。
您应该将测试代码放在与您正在测试的 class 不同的 class 中。 所以你的计算器 class 应该有一个对应的 CalculatorTests class 只包含单元测试。
Check out https://www.tutorialspoint.com/mockito/mockito_spying.htm for info on Mockito spy
which allows you to mock one method of a class you are testing, but make a real call for some other method on the same class.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.