Bel*_*lun 11 java junit unit-testing 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这些是类:
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 {
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
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 )
Run Code Online (Sandbox Code Playgroud)
这里有一个问题:如何让PowerMock找出要查找的构造函数?
有问题的线是suppress.这就是错误的来源.
Sma*_*key 17
也许你的问题为时已晚.我今天遇到了它,并在以下网址找到了解决方案.基本上,您需要指定您的参数类型.
whenNew(MimeMessage.class).**withParameterTypes(MyParameterType.class)**.withArguments(isA(MyParameter.class)).thenReturn(mimeMessageMock);
Run Code Online (Sandbox Code Playgroud)
http://groups.google.com/group/powermock/msg/347f6ef1fb34d946?pli=1
希望它可以帮到你.:)
在你写下你的问题之前我不知道 PowerMock,但做了一些阅读并在他们的文档中发现了这一点。我仍然不确定这是否对您有帮助:
如果超类有多个构造函数,则可以告诉 PowerMock 仅抑制特定的一个构造函数。假设您有一个名为 的类,
ClassWithSeveralConstructors该类有一个采用 a 的构造函数String和另一个采用 anint作为参数的构造函数,并且您只想抑制该String构造函数。您可以使用该suppress(constructor(ClassWithSeveralConstructors.class, String.class));方法来完成此操作。
发现于http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior
这不是你想要的东西吗?
编辑:现在我明白了,你已经尝试过抑制。但你确定你的抑制呼叫正确吗?的第一个参数不是constructor()应该是您想要抑制构造函数的类吗?
| 归档时间: |
|
| 查看次数: |
18674 次 |
| 最近记录: |