JUnit Mockito framework

倖福魔咒の 提交于 2020-01-17 06:05:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!