繁体   English   中英

在 Mockito 中,有什么方法可以模拟 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.**

请找到代码的屏幕截图。

具有 public void test() 和 public double add() 的计算器类

包含 main() 的 TestCalculator 类。我在控制台上低于 o/p 的地方

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM