本文介绍了java模拟自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class MainClass {
public void makeCall() {
CustomObject obj = new CustomObject();
obj.testMethod();
}
}
我想对 makeCall()
进行单元测试.所以我必须模拟上面示例中的 CustomObject
.我使用 Mockito 作为模拟框架.但是当我模拟像 mock(CustomObject.class)
这样的对象时.makeCall()
方法总是调用实际的对象而不是模拟的对象.反正有没有模拟本地对象.请帮忙
I want to unit test the makeCall()
. So i have to mock the CustomObject
in the above sample. I am using Mockito as the mock framework.But when i mock the object like mock(CustomObject.class)
. makeCall()
method always call the actual object not the mocked one.Is there anyway to mock the local objects. Please help
推荐答案
MainClass
的单元测试友好版本应该注入 CustomObject
,例如:
A unit-test-friendly version of your MainClass
should have CustomObject
injected, for example:
public class MainClass {
private CustomObject customObject = new CustomObject(); // a default one if none is provided
public void setCustomObject(CustomObject customObject) {
this.customObject = customObject;
}
public void makeCall() {
this.customObject.testMethod();
}
}
您的测试将如下所示:
CustomObject mockCustomObject = mock(CustomObject.class);
when(mockCustomObject.testMethod()).thenReturn(...);
MainClass sut = new MainClass();
sut.setCustomObject(mockCustomObject);
sut.makeCall();
verify(mockCustomObject).testMethod();
加上Mockito的注解,可以进一步简化为:
With Mockito's annotation, it can be further simplified as:
public class MyClassTest {
@InjectMocks
private MainClass mainClass;
@Mock
private CustomObject mockCustomObject;
@Before
public void setup() {
MockitoAnnotations.initMocks(this); // or use mockito runner
}
@Test
public void testMakeCall() {
when(mockCustomObject.testMethod()).thenReturn(...);
mainClass.makeCall();
verify(mockCustomObject).testMethod();
}
}
这篇关于java模拟自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!