2016-07-07 91 views
0

的方法我有类似下面的类:1类的如何通过模拟参数使用的Mockito和Java的

public class Service { 
    public String method1 (class1, class2){ 
    //do something 
    return result   //Returns a string based on something 
} 
} 

我想通过调用方法“方法1”与嘲笑参数测试类服务(对象Class2)。我没有任何想法,如何使用Mockito做到这一点。任何人都可以帮助我完成最初的推送?

+2

模拟方法的参数并不典型,因为它们通常是面向数据的类型。模拟是处理方法(即功能类型)。但如果你真的想要它,你可以这样做:Foo mock = mock(Foo.class); http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Mockito.html – Dmytro

回答

2

如果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... 
    } 
}