[英]How to unit-test a public method that has private methods in MVP pattern
While using MVP pattern for WinForms I come across scenarios where I call some private methods in my public method of Presenter
and change a few properties of the View.在为 WinForms 使用 MVP 模式时,我遇到了在我的
Presenter
的公共方法中调用一些私有方法并更改视图的一些属性的场景。
How can I unit test these situations efficiently ?如何有效地对这些情况进行单元测试?
public void OnFileNameChanged(string fileName)
{
_settings = FirstPrivateOperation()
if (_settings == null)
{
_view.A = false;
return;
}
var config = SecondPrivateOperation();
if (config == null)
{
_view.B = true;
return;
}
_view.C = true;
}
Some options, based on what you showed, would be:根据您展示的内容,一些选项将是:
_settings
and config
or even the two methods which provide the results into a separate class ( like a configuration kind of thing ) and inject the interface of that class as a dependency at whatever level it makes sense._settings
和config
甚至将结果提供到单独的 class 中的两种方法(就像一种配置一样),并将该 class 的接口作为任何有意义的级别的依赖项注入。 You can then mock those values. I would pursue one of these options.我会追求这些选择之一。
In regards to the View values, I would try to separate that.关于 View 值,我会尝试将其分开。 There are number of issues with this code.
此代码存在许多问题。
OnFileNameChanged
metho and you probably can't change its signature and doesn't return anything.OnFileNameChanged
方法,您可能无法更改其签名并且不返回任何内容。 So, I would separate the code even more.OnFileNameChanged
you assign what you need for the view stuff.OnFileNameChanged
中分配视图所需的内容。 In short, take the logic part out and deal with it somewhere else and test that. You have 3 values that you are assigning to the View object, so make your new method return either one value, or an object with three values, covering each possibility.您有 3 个值要分配给视图 object,因此请让您的新方法返回一个值,或者返回具有三个值的 object,涵盖每种可能性。
public void OnFileNameChanged(string fileName)
{
var calculatedValues = CalculateValues(//might need some params here)
_view.A = calculatedValues.A;
_view.B = calculatedValues.B;
_view.C = calculatedValues.C;
}
public MyReturnType CalculateValues()
{
var result = new MyReturnType();
var config = FirstPrivateOperation();
if ( config == null ) { return result; }
//etc etc
}
public MyReturnType
{
public Whatever A { get;set }
public Whatever B { get;set }
public Whatever C { get;set }
}
you can go even further and deal with the private methods in a different way.您可以进一步 go 并以不同的方式处理私有方法。 you might want to add a separate class to replace them and then that makes theme easier to test / mock as well.
您可能想添加一个单独的 class 来替换它们,然后这也使主题更容易测试/模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.