我有一个Singleton类Svnplugin的getInstance()我需要模拟以返回模拟对象。但这并没有被嘲笑。我正在使用PowerMock和Easymock。
以下是我的测试代码
@Test
@PrepareForTest({SVNPlugin.class})
public void createGlobalUSerTest() throws Exception{
PowerMock.mockStatic(SVNPlugin.class);
SVNPlugin svnPlugin=PowerMock.createMock(SVNPlugin.class);
PowerMock.expectNew(SVNPlugin.class).andReturn(svnPlugin);
EasyMock.expect(SVNPlugin.getInstance()).andReturn(svnPlugin).anyTimes();
EasyMock.expect(svnPlugin.getSynProject("", "", "", "")).andReturn(true);
PowerMock.replay(SVNPlugin.class,svnPlugin);
Future<RpcResult<CreateGlobalUserOutput>>
result=impl.createGlobalUser(getGLobalUser());
PowerMock.verify(svnPlugin,SVNPlugin.class);
Assert.assertNotNull(result);
}
需要模拟的示例代码
SVNPlugin svnplugin = SVNPlugin.getInstance();
checkOutFlg = svnplugin.getSynProject(checkOutLocationAtLocal, svnPath , userName, passWord);
我无法理解我做错了什么。
快速答案是您需要PowerMock Runner。
那么,实际上您不需要模拟new
,因为模拟getInstance
就足够了。
我以为SVNPlugin
是最终的,它证明使用PowerMock创建的模拟合理。所以我尝试了此实现。
public final class SVNPlugin {
public static SVNPlugin getInstance() {
return new SVNPlugin();
}
private SVNPlugin() {}
public boolean getSynProject(String s, String s1, String s2, String s3) {
return false;
}
}
,以下测试正常工作。
@RunWith(PowerMockRunner.class)
public class SVNPluginTest {
@Test
@PrepareForTest(SVNPlugin.class)
public void createGlobalUSerTest() throws Exception{
PowerMock.mockStatic(SVNPlugin.class);
SVNPlugin svnPlugin = PowerMock.createMock(SVNPlugin.class);
EasyMock.expect(SVNPlugin.getInstance()).andStubReturn(svnPlugin);
EasyMock.expect(svnPlugin.getSynProject("", "", "", "")).andReturn(true);
PowerMock.replay(SVNPlugin.class,svnPlugin);
SVNPlugin svnplugin = SVNPlugin.getInstance();
boolean checkOutFlg = svnplugin.getSynProject("", "", "", "");
assertTrue(checkOutFlg);
PowerMock.verify(svnPlugin,SVNPlugin.class);
}
}