单身人士课没有被嘲笑

时间:2017-11-29 05:09:29

标签: java unit-testing mocking powermock easymock

我有一个单例类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);

我无法理解我做错了什么。

1 个答案:

答案 0 :(得分:1)

快速回答是你需要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);
  }
}