java - 我如何在这里模拟最终的内部类
问题描述
我正在为其编写 Junits 的类:
public class AImpl implements AInterface {
public String method1(String id) throws Exception {
String s = Service.Factory.getInstance().generate(id);
return s;
}
}
要使用其 Inner 类实例化的接口:
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);
}
解决方案
如果我能很好地理解您不清晰的代码,您需要这个junit:
@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 类:在这里您需要一个私有构造函数才能正确实现单例模式。
推荐阅读
- python - 如何组合数据框列
- javascript - 使弹出窗口的高度扩展到其子项的内容
- c - 双向链表替代实现
- python - 通过导入csv在python中读取一个excel文件
- javascript - 在javascript运行时,堆栈的“帧”和队列的“消息”有什么区别?
- rust - 从通道读取并使用 poll_fn 和 try_ready 的 Tokio 未来永远不会完成
- objective-c - 在什么情况下 [NSDocument fileURL] 可以为零?
- osc - 如何启动和更改 Synth?
- authentication - 漫游到不同 AP 时的身份验证错误
- javascript - Javascript更改事件目标不透明度