我正在学习使用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代码与JUnit测试用例是100%兼容的,还是我遗漏了一些要点。
发布于 2017-02-20 19:19:35
你可以用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,这是一种糟糕的做法。
发布于 2017-02-20 18:25:38
当你需要一个被模仿的对象时,你需要使用被模仿的类。如果你想要一个实际类的行为,比如你试图调用的道名的引用,你需要使用spy。
Junit:
ChildClass childClass = Mockito.spy(new ChildClass());
发布于 2020-05-28 03:22:04
有关模拟示例,请阅读此blog。
https://stackoverflow.com/questions/42351637
复制