【问题标题】:Mocking a static class method that is inside a non static class模拟非静态类中的静态类方法
【发布时间】:2016-04-20 11:36:16
【问题描述】:

如果我有

public class ServiceParameters {

    private String ABC;

    public ServiceParameters(ServiceParametersBuilder builder) {
        this.ABC = builder.ABC;
    }

    public static class ServiceParametersBuilder {
        private String ABC;

        public ServiceParameters build() {
            return new ServiceParameters(this);
        }
    }
}

以及在其他地方调用的代码

serviceParameters = new ServiceParameters.ServiceParametersBuilder().build();

我如何模拟,以便上面的代码使用 EasyMock 和 PowerMock 返回一个模拟的 ServiceParameters

【问题讨论】:

    标签: mocking powermock easymock


    【解决方案1】:

    你不解释,你的测试应该是什么。无论如何,没有必要模拟 ServiceParameters:它什么都不做,应该被替换(或在单元测试方面模拟)。您可以创建它并继续您的测试。 如果 ServiceParameters 有一个方法:

    public int someMethod()...
    

    从数据库中读取文件或查询或调用第三方服务等。它可以模拟如下测试:

    public class TestServiceParameters {
        @Mock
        ServiceParameters parametersMock;
    
        @Test
        public void test() {
            Mockito.when(parametersMock.someMethod()).thenReturn(1);
            //.... test stuff here
        }
    }
    

    我还有一些例子 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-17
      • 2011-07-11
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2010-12-21
      相关资源
      最近更新 更多