【问题标题】:How to pass mock parameter in a method using Mockito & Java如何在使用 Mockito 和 Java 的方法中传递模拟参数
【发布时间】:2016-07-07 11:38:24
【问题描述】:

我有如下课程:

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

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

【问题讨论】:

标签: java unit-testing junit mocking mockito


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2020-12-08
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多