【问题标题】: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?在 Mockito 中,有什么方法可以模拟具有需要模拟的方法和需要测试的方法的类(而不是接口)?
【发布时间】:2020-07-24 18:52:52
【问题描述】:

我试图模拟具有该方法的类

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

【问题讨论】:

  • 您的验证语句应该在断言语句之后。
  • 你测试的目的是什么?您要测试的方法实现本身是模拟的?
  • @Mensur Qulami 我尝试在断言之后添加验证语句,但控制台上未打印 add(double in1, double in2) 方法“模拟”中的记录器。输出是“Jul 26, 2020, 10:43:39 PM main.TestCalculator main INFO: Result: true” 测试的目的是检查我们是否可以在同一个类中测试一个模拟对象和方法。 (我不想用接口和SpringBoot注解)
  • @PrashantChinchkar 你可能标记了错误的用户。

标签: java unit-testing junit mocking mockito


【解决方案1】:

您的verify 语句应该在您正在验证的方法被调用之后出现。在这种情况下,您尝试验证是否调用了 add 方法,但在您的验证语句之前并未调用该方法。

您应该将测试代码放在与您正在测试的类不同的类中。所以你的 Calculator 类应该有一个对应的 CalculatorTests 类,它只包含单元测试。

查看https://www.tutorialspoint.com/mockito/mockito_spying.htm 以获取有关 Mockito spy 的信息,它允许您模拟您正在测试的类的一个方法,但对同一类的某些其他方法进行真正的调用。

【讨论】:

    猜你喜欢
    • 2013-08-18
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多