我正在为其编写Junits的类:
public class AImpl implements AInterface {
public String method1(String id) throws Exception {
String s = Service.Factory.getInstance().generate(id);
return s;
}
}
要使用其内部类实例化的接口:
public interface Service {
String generate(String var1) throws Exception;
public static final class Factory {
private static Service instance = null;
public Factory() {
}
public static final Service getInstance() {
if (instance == null) {
instance = (Service)EnterpriseConfiguration.getInstance().loadImplementation(Service.class);
}
return instance;
}
}
}
我已经尝试过powerMockito,但是它不起作用。
@Test public void generateTest() throws Exception { Service.Factory innerClassMock = mock(Service.Factory.class); String id= "id"; whenNew(Service.Factory.class).withArguments(anyString()).thenReturn(innerClassMock); whenNew(innerClassMock.getInstance().generate("hjgh")).withAnyArguments().thenReturn(id); id= AImpl.generate("hjgh"); Assert.assertEquals("id", id); }
@RunWith(PowerMockRunner.class)
@PrepareForTest({Service.Factory.class})
public class AImplTest {
private Service serviceMock;
@Before
public void setUp() {
PowerMockito.mockStatic(Service.Factory.class);
serviceMock = Mockito.mock(Service.class);
PowerMockito.when(Service.Factory.getInstance()).thenReturn(serviceMock);
}
@Test
public void generateTest() throws Exception {
Mockito.doReturn("mockid").when(serviceMock).generate(Mockito.anyString());
Assert.assertEquals("mockid", new AImpl().method1("aaa"));
}
}
这里是我的依赖项:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.28.2</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 --> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>2.0.4</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 --> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.4</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.powermock/powermock-core --> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> <version>2.0.4</version> <scope>test</scope> </dependency>
已经说过,我将更改您的Service.Factory类:这里您需要一个私有构造函数,以便正确地实现单例模式。