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

标签 java unit-testing junit mocking mockito

我的类(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/

相关文章:

AngularJS 服务 Jasmine 单元测试未刷新请求错误

java - 如何测试struts 2.0.x应用程序

java - 无法实例化类 : org. apache.naming.java.javaURLContextFactory

java - HttpServletRequest 类型未定义 getDispatcherType()

java - 如何使用 HttpServletRequest(Spring Framework) 传递同名的多个值?

.net - .NET有没有 "advanced"测试框架?

eclipse - JUnit + Maven + Eclipse : Why @BeforeClass does not work?

java - JFace 表格查看器 : Make cell background-color blink

java - 获取一个字符串在另一个字符串中出现的次数

spring - TestNG - 仅当定义了 6 个或更多测试时才会出现异常