我的类(class)如下:
public class Service {
public String method1 (class1, class2){
//do something
return result //Returns a string based on something
}
}
我想通过使用模拟参数(Class1 和 Class2 的对象)调用方法“method1”来测试类 Service。我不知道如何使用 Mockito 执行此操作。有人可以帮助我进行初始推送吗?
最佳答案
如果 class1 和 class2 是简单值或 POJO,则不应模拟它们:
public class ServiceTest {
Service service;
@Before
public void setup() throws Exception {
service = new Service();
}
@Test
public void testMethod1() throws Exception {
// Prepare data
Class1 class1 = new Class1();
Class2 class2 = new Class2();
// maybe set some values
....
// Test
String result = this.service.method1(class1, class2);
// asserts here...
}
}
如果 class1 和 class2 是更复杂的类,比如服务,将它们作为参数传递会很奇怪......但是我不想讨论你的设计,所以我只会写一个例子来说明如何做到这一点:
public class ServiceTest {
Service service;
@Mock Class1 class1Mock;
@Mock Class2 class2Mock;
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
service = new Service();
}
@Test
public void testMethod1() throws Exception {
// Mock each invocation of the "do something" section of the method
when(class1Mock.someMethod).thenReturn(someValue1);
when(class2Mock.someMethod).thenReturn(someValue2);
....
// Test
String result = this.service.method1(class1Mock, class2Mock);
// asserts here...
}
}
关于java - 如何使用 Mockito 和 Java 在方法中传递模拟参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38244496/