2017-02-20 62 views
0

我正在学习用的Mockito框架JUnit的,我想对我的服务代码编写测试用例: -的JUnit的Mockito框架

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%兼容,或者我错过了某些观点。

+0

你在哪里为'employeeInstance'创建模拟? –

+0

使用@Mock EmployeeInstance employeeInstance;在测试课上。 –

+0

你有'thenReturn(employeeInstance)',但是在下一行中,你正在使用'employeeInstanceMocked'。这是一个错字?你希望这些都是一样的。 –

回答

0

当需要模拟对象时,您需要使用模拟类。如果你想要一个实际的类的行为,例如你尝试打电话给你的道的引用,你需要使用间谍。

的Junit:

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

您测试了这个,还是仅仅是一个猜测? –

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