我有一个单例类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运行器。

然后,实际上您无需模拟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);
  }
}

关于java - 单例类不被 mock ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47545464/

10-10 06:50