java - 模拟带参数的构造函数

标签 java junit mocking mockito powermock

我有一门课如下:

public class A {
    public A(String test) {
        bla bla bla
    }

    public String check() {
        bla bla bla
    }
}

构造函数 A(String test)check() 中的逻辑是我试图模拟的东西。我想要任何调用,例如: new A($$$any string$$$).check() 返回一个虚拟字符串 "test".

我试过了:

 A a = mock(A.class); 
 when(a.check()).thenReturn("test");

 String test = a.check(); // to this point, everything works. test shows as "tests"

 whenNew(A.class).withArguments(Matchers.anyString()).thenReturn(rk);
 // also tried:
 //whenNew(A.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(rk);

 new A("random string").check();  // this doesn't work

但它似乎不起作用。 new A($$$any string$$$).check() 仍在执行构造函数逻辑,而不是获取 A 的模拟对象。

最佳答案

您发布的代码适用于我最新版本的 Mockito 和 Powermockito。也许你还没有准备好A? 试试这个:

A.java

public class A {
     private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

MockA.java

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}

这两个测试都应该通过 mockito 1.9.0、powermockito 1.4.12 和 junit 4.8.2

关于java - 模拟带参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13364406/

相关文章:

java - 如何在 Junit 中使 `_logger.isDebugEnabled()` 条件为假?

java - 使用google api explorer将数据上传到google云存储

Java hibernate 分离条件、计数/拥有、查询

java - 我已经在 gradle 编译 'com.firebaseui:firebase-ui-auth:2.3.0' 中编写了这一行,但仍然收到错误 "cannot resolve symbol ' Auth UI'”

java - @Ignore 对 JUnit XML 输出做了什么?

java - @After 注释在 JAVA 7 中使用 JUnit 时首先运行

java - java中基于字符的字符串分割操作

PhpUnit 模拟 : function undefined

unit-testing - 使模拟实现记录任意数量的参数

ruby-on-rails - 如何正确使用模拟?