如果1類和類2是簡單的值或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...
}
}
如果1類和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...
}
}
模擬方法的參數並不典型,因爲它們通常是面向數據的類型。模擬是處理方法(即功能類型)。但如果你真的想要它,你可以這樣做:Foo mock = mock(Foo.class); http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Mockito.html – Dmytro