Mru*_*ukh 6 java junit unit-testing mocking mockito
我正在编写一个使用JUNIT + Mockito测试方法的单元测试:
public someObject methodUnderTest(){
SomeObject obj = SomeAbstractClass.someMethod();
if(obj!=null){
obj.someOtherMethod();
}
return someThing;
}
Run Code Online (Sandbox Code Playgroud)
我想模拟abstract Class "SomeAbstractClass"上面代码片段中提到的调用,所以我可以验证对"obj"的调用,如:
verify(SomeAbstractClass).someMethod();
verify(obj).someOtherMethod();
Run Code Online (Sandbox Code Playgroud)
我尝试过使用mockito功能,例如:Mockito.CALLS_REAL_METHODS Mockito.RETURNS_MOCKS
但由于SomeAbstractClass不可用的依赖项,它们不起作用.
注意:
1)SomeObject是一个接口.
2)我需要一种技术来测试上面的代码片段.我被限制使用上面的代码片段,不能更改代码片段.
假设:如果你编写单元测试,我想你仍然可以稍微修改测试方法。
解决方案:
Run Code Online (Sandbox Code Playgroud)public someObject methodUnderTest() { SomeObject obj = getSomeObject(); if(obj!=null){ obj.someOtherMethod(); } return someThing; } protected SomeObject getSomeObject() { return SomeAbstractClass.someMethod(); }
Run Code Online (Sandbox Code Playgroud)private ClassUnderTest classUnderTest; @Before public void setUp() { classUnderTest= new ClassUnderTest(); classUnderTest = Mockito.spy(classUnderTest); } @Test public void test() { SomeObject someObject = Mockito.mock(SomeObject.class); when(classUnderTest.getSomeObject()).thenReturn(someObject); classUnderTest.methodUnderTest(); verify(someObject).someOtherMethod(); } @Test public void testNull() { when(classUnderTest.getSomeObject()).thenReturn(null); classUnderTest.methodUnderTest(); verify(something); }