Đây là thử nghiệm:Làm thế nào để giả lập đối tượng với hàm tạo có một lớp?
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);
}
}
Đây là các lớp:
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 {
}
Đây là lỗi:
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)
Ở đây có câu hỏi: làm thế nào tôi có thể làm PowerMock tìm ra những gì constructor cần tìm?
Dòng có vấn đề là suppress
. Đó là nơi lỗi xuất phát.
Điều gì sẽ xảy ra khi bạn loại bỏ hàm tạo CollaboratorToBeMocked (java.lang.Class.class)? Nó có hoạt động không? – Davidann
bạn có nghĩa là, khi tôi loại bỏ các constructor khác ... có, nếu tôi loại bỏ các nhà xây dựng với InjectedIntoCollaborator, nó hoạt động – Belun