【问题标题】:Mocking/stubbing whether or debug log is enabled?模拟/存根是否启用或调试日志?
【发布时间】:2017-11-21 21:03:15
【问题描述】:

如何编写一个模拟测试来验证不可访问的属性 (debugLog) 是否设置为 true?我是否试图找到一种方法来找到财产的价值?我是否验证 console.debug 已设置?在这种情况下间谍是否有意义,还是我应该使用存根?

X 级

let showDebugLogs = false,
debugLog = _.noop

/**
 * Configures Class X instances to output or not output debug logs.
 * @param {Boolean} state The state.
 */
exports.showDebugLogs = function (state) {
    showDebugLogs = state;
    debugLog = showDebugLogs ? console.debug || console.log : _.noop;
};

单元测试

    describe('showDebugLogs(state)', function () {
        let spy;
        it('should configure RealtimeEvents instances to output or not output debug logs', function () {
            spy = sinon.spy(X, 'debugLog');
            X.showDebugLogs(true);
            assert.strictEqual(spy.calledOnce, true, 'Debug logging was not enabled as expected.');
            spy.restore();
        });
    });

【问题讨论】:

    标签: unit-testing mocha.js sinon sinon-chai


    【解决方案1】:

    模拟测试用于将被测类从其环境中“隔离”出来,以减少其副作用并提高其测试能力。例如,如果您正在测试一个对 Web 服务器进行 AJAX 调用的类,您可能不想:

    1) wait for AJAX calls to complete (waste of time)
    2) observe your tests fall apart because of possible networking problems
    3) cause data modifications on the server side
    

    等等。

    所以你要做的是“模拟”你的代码的一部分,它会调用 AJAX,并且取决于你的测试:

    1) return success and response accompanying a successful request
    2) return an error and report the nature of the point of failure to see how your code is handing it.
    

    对于您的案例,您需要的只是一个简单的单元测试案例。如果这是您真正想要的,您可以使用自省技术来断言对象的内部状态。但是,这带有一个警告:不鼓励请参阅底部的注释

    应该进行单元测试来测试对象的行为或公共状态。所以,你真的不应该关心类的内部结构。

    因此,我建议您重新考虑您要测试的内容并找到更好的测试方法。

    建议:您可以模拟记录器来进行测试,而不是检查班级中的标志。并至少编写两个测试用例如下:

    1) When showDebugLogs = true, make sure log statement of your mock logger is fired
    2) When showDebuLogs = false, log statement of your mock logger is not called. 
    

    注意事项:两派之间一直存在长期争论:一组主张私有成员/方法是实现细节,应该直接测试,以及另一个反对这个想法的团体:

    Excerpt from a wikipedia article:

    TDD 的从业者之间存在一些争论,记录在他们的 博客和其他著作,至于测试私人是否明智 无论如何方法和数据。一些人认为私人成员仅仅是 可能会改变的实现细节,应该被允许这样做 不破坏测试数量。因此,应该足以 通过其公共接口或通过其子类测试任何类 接口,一些语言称之为“受保护”接口。[29] 其他人说,功能的关键方面可能会在 私有方法并直接对其进行测试提供了较小的优势 以及更直接的单元测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多