【问题标题】:JUnit Mockito frameworkJUnit Mockito 框架
【发布时间】:2017-02-20 18:14:43
【问题描述】:

我正在学习带有 Mockito 框架的 JUnit,我尝试在我的服务代码上编写测试用例:-

ChildClass childClass = (ChildClass)(employeeDao.callMethod().getClassRef());

JUnit 测试用例:-

ChildClass childClass = new ChildClass();
Mockito.when(employeeDao.callMethod().getClassRef()).thenReturn(childClass);

但是得到 java.lang.NullPointerException

然后尝试将方法调用拆分为两个单独的语句,例如:-

ChildClass childClass = new ChildClass();
Mockito.when(employeeDao.callMethod()).thenReturn(employeeInstance);
Mockito.when(employeeInstanceMocked.getClassRef()).thenReturn(childClass);

但由于 Mockito 返回 SuperClassObject 仍导致对象转换异常,但代码正在转换为 ChildClass 对象。当前的 Java 代码是否 100% 兼容以使用 JUnit 测试用例进行测试,或者我遗漏了一些要点。

【问题讨论】:

  • 你在哪里为employeeInstance创建模拟?
  • 使用@Mock EmployeeInstanceemployeeInstance;在测试课上。
  • 你有thenReturn(employeeInstance),但在下一行,你使用的是employeeInstanceMocked。这是印刷错误吗?你希望这些是一样的。
  • 您的第一个 sn-p 显然会给出 NullPointerException,因为模拟上的 callMethod() 将返回 null,除非您已将其存根。如果您在第一个存根调用中使用的实际上是 employeeInstanceMocked,那么您的第二个 sn-p 应该可以工作。你说你有“对象转换异常”——这不是我熟悉的异常。它的确切文字是什么?
  • 处理程序执行导致异常:SuperClass$$EnhancerByMockitoWithCGLIB$$467cd658 cannot be cast to ChildClass

标签: java junit mocking mockito


【解决方案1】:

您可以使用 Mockito 做到这一点。来自documentation的示例:

Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);

// note that we're stubbing a chain of methods here: getBar().getName()
when(mock.getBar().getName()).thenReturn("deep");

// note that we're chaining method calls: getBar().getName()
assertEquals("deep", mock.getBar().getName());

但正如文档中所述,由于违反Law of Demeter,这是一种不好的做法。

【讨论】:

    【解决方案2】:

    当你想要一个模拟对象时,你需要使用模拟类。如果你想要一个实际类的行为,比如你试图调用的 dao 的引用,你需要使用 spy.

    朱尼特:

    ChildClass childClass = Mockito.spy(new ChildClass());
    

    【讨论】:

    • 您是否对此进行了测试,还是只是猜测?
    【解决方案3】:

    阅读此blog 以获取 mockito 示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多