英文:
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?
问题
以下是您要求的翻译内容:
我尝试模拟一个具有以下方法的类:
public double add(double in1, double in2)
和
@Test
public void test()
当我运行代码时,我得到了一个错误:
**期望但未调用:
calculator.add(10.0, 20.0);
-> 在 main.Calculator.test(Calculator.java:20)
实际上,与此模拟没有发生任何交互。**
请查看代码的屏幕截图。
Jul 24, 2020 11:48:05 PM main.TestCalculator main
INFO: test(main.Calculator):
**期望但未调用:
calculator.add(10.0, 20.0);
-> 在 main.Calculator.test(Calculator.java:20)
实际上,与此模拟没有发生任何交互。**
Jul 24, 2020 11:48:05 PM main.TestCalculator main
INFO: 结果:false
英文:
I was trying to mock the class which has the method
public double add(double in1, double in2)
and
@Test
public void test()
when I run code, I got an error
**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.**
Please find the screenshot of the code.
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
答案1
得分: 0
你的verify
语句应该放在你要验证的方法被调用之后。在这种情况下,你试图验证add
方法是否被调用,但是该方法在你的验证语句之前并未被调用。
你应该将测试代码放在与被测试类不同的类中。所以你的Calculator类应该有一个对应的CalculatorTests类,其中只包含单元测试。
查看https://www.tutorialspoint.com/mockito/mockito_spying.htm 了解关于Mockito spy
的信息,它允许你模拟要测试的类的一个方法,但对于同一类中的其他方法进行真实调用。
英文:
Your verify
statement should come after the method you are verifying has been invoked. In this case, you are trying to verify that the add
method was invoked, but that method isn't called before your verify statement.
You should put your test code in a different class separate from the class you are testing. So your Calculator class should have a corresponding CalculatorTests class that contains just the unit tests.
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论