【问题标题】:Properly test static method in Android在Android中正确测试静态方法
【发布时间】:2017-09-27 11:59:44
【问题描述】:

我正在尝试使用以下原理测试一个Android应用程序

  • 直接测试公共方法
  • 测试私有方法是测试公共方法的副作用
  • 独立测试静态方法

出于这个原因,我希望只依赖 JUnit 和 Mockito 进行测试,而不是冒着滥用 PowerMockito 等框架的风险

但是在这种情况下测试公共方法时,我陷入了困境

public class ClassA {
    public void publicMethod(String id) {
        // something
        privateMethod(id);
    }

    public void privateMethod(String id) {
        // something
        StaticClass.staticMethod(id);
    }
}

因为在这里我可以为publicMethod写一个测试,但是我面临的问题

  • 如何防止 StaticClass.staticMethod 触发(模拟其行为/响应)?因为该方法可以在内部触及从 DB、HttpConnections 到 Context 等的任何内容(尤其是如果它来自我自己没有编写的类)

【问题讨论】:

    标签: java android unit-testing static mockito


    【解决方案1】:

    解决办法是:

    1. 将您的静态实用程序类包装在一个可模拟对象中。
    2. 不要在被测系统 (SUT) 中调用静态实用程序,而是传递对包装类的依赖项。
    3. 在您的测试的 @Before 方法中使用模拟包装类调用 SUT 的构造函数。

    这符合 OOP 的封装原则(BTW 静态类可以破坏)。示例:

    class WrappedStaticClass {
    
        void wrappedStaticMethod() {
            StaticClass.staticMethod();
        }
    }
    

    重构后的ClassA 现在看起来像这样:

    public class ClassA {
    
        private final WrappedStaticClass wrappedStaticClass;
    
        public ClassA(WrappedStaticClass wrappedStaticClass) {
            this.wrappedStaticClass = wrappedStaticClass;
        }    
    
        public void publicMethod(String id) {
            // something
            privateMethod(id);
        }
    
        private void privateMethod(String id) {
            // something
            wrappedStaticClass.wrappedStaticMethod(id);
        }
    }
    

    您的测试现在看起来像这样:

    @Mock WrappedStaticClass mockWrappedStaticClass;
    
    //system under test
    ClassA classA;
    
    @Before
    public void setUp() {
        MockitoAnnotations.init(this);
        classA = new ClassA(mockWrappedStaticClass);
    }
    
    @Test
    public void testCallsWrappedStaticClass() {
        //act
        classA.publicMethod(1);
    
        //assert
        verify(mockWrappedStaticClass).wrappedStaticMethod();
    }
    

    【讨论】:

    • 非常感谢大卫,非常感谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-12
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多