例如,我有以下处理程序:
@Component
public class MyHandler {
@AutoWired
private MyDependency myDependency;
public void someMethod(Object parameter) {
...
ThirdPartyClass thirdPartyObject = new ThirdPartyClass(parameter);
thirdPartyObject.unnecessaryMethod();
...
}
}
为了测试这一点,我想写这样的东西:
@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {
@InjectMocks
MyHandler myHandler;
@Mock
MyDependency myDependency;
@Test
public void testSomeMethod() {
...
myHandler.someMethor(parameter);
...
}
}
我想避免打电话给unnecessaryMethod()
.有什么办法可以做到这一点吗?
如果unnecessaryMethod()
是静态的,那么我可以使用PowerMockito来模拟它,但是PowerMockito可以在我的情况下提供帮助吗?
我找到了答案:
public class MyHandler {
public void someMethod() {
Utils utils = new Utils(10);
System.out.println("Should be 1 : " + utils.someMethod());
}
}
一些实用工具类:
public class Utils {
private int value = 5;
Utils () {
System.out.println("Should be mocked");
}
Utils (int param) {
this.value = param;
System.out.println("Should be mocked");
}
public int someMethod() {
System.out.println("Should be mocked");
return value;
}
}
和测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyHandler.class)
public class MyHandlerTest {
@InjectMocks
MyHandler myHandler;
@Test
public void testMain() throws Exception {
Utils utils = mock(Utils.class);
when(utils.someMethod()).thenReturn(1);
whenNew(Utils.class).withArguments(anyInt()).thenReturn(utils);
myHandler.someMethod();
}
}
控制台输出将为: Should be 1 : 1
相关问题