如何使用 Mockito & Java 在方法中传递模拟参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38244496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:15:17  来源:igfitidea点击:

How to pass mock parameter in a method using Mockito & Java

javaunit-testingjunitmockingmockito

提问by Sumit

I have class like the following:

我有如下课程:

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

I want to test the class Service by calling the method 'method1' with mocked parameter (objects of Class1 & Class2). I don't have any idea, how to do this using Mockito.Can anyone help me with the initial push ?

我想通过使用模拟参数(Class1 和 Class2 的对象)调用方法“method1”来测试类 Service。我不知道如何使用 Mockito 做到这一点。有人可以帮助我进行初始推送吗?

回答by Lorenzo Murrocu

If class1 and class2 are simple values or POJOs, you should just not mock them:

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

If class1 and class2 are more complicated classes, like services, it is strange to pass them as arguments... However I don't want to discuss your design, so I will just write an example of how you can do it:

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