如何模拟修改私有变量的私有方法? [英] How mock private method that modify private variables?

查看:151
本文介绍了如何模拟修改私有变量的私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改私有变量的模拟私有方法?

How mock private method that modify private variables?

class SomeClass{
    private int one;
    private int second;

    public SomeClass(){}

    public int calculateSomething(){
        complexInitialization();
        return this.one + this.second;
    }

    private void complexInitialization(){
        one = ...
        second = ...
    }
}


推荐答案

你没有,因为你的测试将取决于它正在测试的类的实现细节,因此将是脆弱的。您可以重构代码,使您当前正在测试的类依赖于另一个对象来进行此计算。然后你可以模拟被测试类的这种依赖性。或者您将实现细节留给类本身并充分测试它的可观察行为。

You don't, because your test will depend on implementation details of the class it is testing and will therefore be brittle. You could refactor your code such that the class you are currently testing depends on another object for doing this calculation. Then you can mock this dependency of the class under test. Or you leave the implementation details to the class itself and sufficiently test it's observable behavior.

您可能遇到的问题是您没有完全将命令和查询分离到您的类。 calculateSomething 看起来更像是一个查询,但 complexInitialization 更像是一个命令。

The problem you could suffer from is that you are not exactly separating commands and queries to your class. calculateSomething looks more like a query, but complexInitialization is more of a command.

这篇关于如何模拟修改私有变量的私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆