如何使用带类的构造函数来模拟对象?
这是测试:如何使用带类的构造函数来模拟对象?
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
。这是错误来自的地方。
直到你写下你的问题,我才知道PowerMock,但是做了一些阅读,并在他们的文档中找到了它。不过我真的不知道如果这能帮助你:
如果超类有几个 构造有可能告诉 PowerMock只抑制特定 之一。假设您有一个名为 的类,它具有 一个构造函数,它接受一个字符串 ,另一个构造函数将一个 int作为参数,而您只希望 禁止String构造函数。 您可以使用
suppress(constructor(ClassWithSeveralConstructors.class, String.class));
方法来做到这一点。
发现在http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior
是不是你想要的东西吗?
编辑:现在我明白了,你已经试过压制。但是你确定你有压制电话吗?是不是constructor()
的第一个参数应该是您想要抑制构造函数的类?
你是对的。我的压力是一团糟。不过,它仍然不起作用,我用`suppress(构造函数(CollaboratorToBeMocked.class,InjectedIntoCollaborator.class));` – Belun 2011-02-11 08:55:22
也许你的问题已经太晚了。我今天遇到了它,并在以下网址找到了解决方案。基本上,你需要指定你的参数类型。
whenNew(MimeMessage.class).**withParameterTypes(MyParameterType.class)**.withArguments(isA(MyParameter.class)).thenReturn(mimeMessageMock);
http://groups.google.com/group/powermock/msg/347f6ef1fb34d946?pli=1
希望它可以帮助你。 :)
当您删除CollaboratorToBeMocked(java.lang.Class.class)构造函数时会发生什么?那它有用吗? – Davidann 2011-02-10 16:07:45
你的意思是,当我删除其他构造函数...是的,如果我删除InjectedIntoCollaborator的构造函数,它的工作原理 – Belun 2011-02-10 16:09:32