首页 > 解决方案 > 如何模拟其对象在测试方法之外初始化的方法?

问题描述

我有一堂课

public class Authentication {
    private Timer timer;

    public Authentication(){
        // constructor
    }

    public void authenticate(){
        // Initialize timer in this method
        timer = new RouterTimer(FAKE_PARAM);
        testingMethod();
    }

    @VisibleForTesting
    void testingMethod(){
        timer.method();
        // other stuff
    }
}

我有一个 Timer 对象作为类属性,但它没有在构造函数中初始化,它在 authenticate() 中初始化。

我正在为 编写单元测试testingMethod(),但测试失败了,因为它timer为 null 并且调用 method() 将引发 NullPointerException。我无法使用类的构造函数初始化计时器。我无法调用 authenticate()初始化,因为该方法将调用testingMethod().

在这种情况下,我该如何模拟或做其他事情?

标签: javaunit-testingjunit

解决方案


你为什么要测试私有方法?将您的代码拆分为逻辑部分并分别测试它们。此外,您正在破坏 SRP ( https://en.wikipedia.org/wiki/Single-responsibility_principle )。方法 authenticate() 不应该初始化任何东西。


推荐阅读