[英]How to mock a function which does not return anything in java
public class Service1 {
private Service2 service2;
// FunctionA
private FuncA(Object1 obj1) {
/*
code to make Obj2 from Obj1
*/
service2.FuncB(obj2);
}
}
public class Service2 {
// FunctionB
private FuncB(Object2 obj) {
obj.field=value;
}
}
I am trying to write Unit Test Case for Func A (as mentioned above) and for that need to mock Func B(as mentioned above). 我正在尝试为Func A(如上所述)编写单元测试用例,并且为此需要模拟Func B(如上所述)。 Pls.
请 help how can I do that in Java 7.
帮助我如何在Java 7中做到这一点。
Ps. 附言 Newbie to Java
Java新手
You need to set the service2
member in your Service1
class, that you are going to test, to a mock object created by your mocking framework. 您需要将要测试的
Service1
类中的service2
成员设置service2
模拟框架创建的模拟对象。 This could look something like this: 可能看起来像这样:
public class Service1Test {
@Mock
private Service2 service2;
@InjectMocks // service2 mock will be injected into service1
private Service1 service1;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void doTest() {
Object someObject = null; // create object matching your needs
service1.FuncA(someObject);
Object someOtherObj = null; // create object matching your needs
verify(service2, times(1)).FuncB(someOtherObj);
// perform additional assertions
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.