java - 如何使用带有类的构造函数模拟对象?

标签 java unit-testing junit mockito powermock

这是测试:

import static junit.framework.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

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

@RunWith(PowerMockRunner.class)
@PrepareForTest( {ClassUnderTesting.class} )
public class ClassUnderTestingTest {

    @Test
    public void shouldInitializeMocks() throws Exception {
        CollaboratorToBeMocked mockedCollaborator = mock(CollaboratorToBeMocked.class);

            suppress(constructor(CollaboratorToBeMocked.class, InjectedIntoCollaborator.class));

        whenNew(CollaboratorToBeMocked.class)
            .withArguments(InjectedAsTypeIntoCollaborator.class)
            .thenReturn(mockedCollaborator);

        new ClassUnderTesting().methodUnderTesting();

        assertTrue(true);
    }
}

这些是类:

public class ClassUnderTesting {

    public void methodUnderTesting() {
        new CollaboratorToBeMocked(InjectedAsTypeIntoCollaborator.class);
    }

}

public class CollaboratorToBeMocked {

    public CollaboratorToBeMocked(Class<InjectedAsTypeIntoCollaborator> clazz) {
    }

    public CollaboratorToBeMocked(InjectedIntoCollaborator someCollaborator) {
    }

    public CollaboratorToBeMocked() {
    }

}

public class InjectedAsTypeIntoCollaborator {

}

public class InjectedIntoCollaborator {

}

这是错误:

org.powermock.reflect.exceptions.TooManyConstructorsFoundException: Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're refering to.
Matching constructors in class CollaboratorToBeMocked were:
CollaboratorToBeMocked( InjectedIntoCollaborator.class )
CollaboratorToBeMocked( java.lang.Class.class )

问题来了:如何让 PowerMock 找出要查找的构造函数?

有问题的行suppress。这就是错误的来源。

最佳答案

也许你的问题来不及了。今天遇到了,在下面的url找到了解决方案。基本上,您需要像这样指定参数类型。

whenNew(MimeMessage.class).**withParameterTypes(MyParameterType.class)**.withArguments(isA(MyParameter.class)).thenReturn(mimeMessageMock); 

http://groups.google.com/group/powermock/msg/347f6ef1fb34d946?pli=1

希望对您有所帮助。 :)

关于java - 如何使用带有类的构造函数模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4959489/

相关文章:

java - 如何完全测试内部具有 System.getenv ("name") 操作的构造函数的覆盖率

java - 将位图转换为 java.awt.image.BufferedImage

java - ASM ClassReader 无法解析类文件 - 可能是由于不支持新的 Java 类文件版本 - 我正在使用 Apache 7 和 JDK 1.8

java - neo4j 执行引擎 NoClassDefFoundError CypherOptionParser

c# - 尝试使用 webgrid 对 Controller 进行单元测试时,HttpContext 为空

unit-testing - 单元测试第三方ORM

java - 象夫 : To read a custom input file

unit-testing - 如何Str::shouldReceive? ( mock Illuminate\Support\Str)

java - 私有(private)构造函数 junit/emma 的覆盖范围

java - 如何测试使用 JPA 存储库的特定 javax 自定义 validator ?