问题
I am learning the JUnit with Mockito framework, I tried writing test cases on my service code as:-
ChildClass childClass = (ChildClass)(employeeDao.callMethod().getClassRef());
JUnit test case:-
ChildClass childClass = new ChildClass();
Mockito.when(employeeDao.callMethod().getClassRef()).thenReturn(childClass);
But getting java.lang.NullPointerException
Then tried splitting the method calls in two seperate statements like:-
ChildClass childClass = new ChildClass();
Mockito.when(employeeDao.callMethod()).thenReturn(employeeInstance);
Mockito.when(employeeInstanceMocked.getClassRef()).thenReturn(childClass);
But still getting the object cast exception due to Mockito is returning SuperClassObject but code is casting into ChildClass Object. Is the current Java code is 100% compatible to test with JUnit test case or I am missing some point.
回答1:
You can do this with Mockito. Example from 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());
But as mentioned in documentation it is bad practice due to violation of Law of Demeter.
回答2:
You need to use mocked class when you want a mocked object. If you want the behavior of an actual class such as the reference of the dao you tried to call you need to use spy.
Junit:
ChildClass childClass = Mockito.spy(new ChildClass());
来源:https://stackoverflow.com/questions/42351637/junit-mockito-framework