【问题标题】:moq getting nested struct from the testing classmoq 从测试类中获取嵌套结构
【发布时间】:2014-05-19 08:25:59
【问题描述】:

我正在为以下类遗留类编写单元测试

Class myLegacyClassPresenter
{
  private MethodA(){}
  private propertyA {get; set;}
  private MethodB(YearValue value){}

 //some more properties & method goes here

 private struct YearValue
 {
    public static int One { get { return 365; } }
    public static int Two { get { return 730; } }
 } 
}

这是我的单元测试。

public void mytest()
{
 //some initializations
 var view = myLegacyView();
 var service = new Mock<ILegacyService>();
 var presenter = new myLegacyClassPresenter(view, service);
 var privateObject = new PrivateObject(presenter);

 //I can access all private methods and properties as follows
 privateObject.invoke("MethodA");
 privateObject.GetProperty("propertyA")

// But How can I get the the Struct Year value to pass to MethodB
privateObject.Invoke("MethodB", new object[]{YearValue.One}); //Compile Error for YearValue 

//I can't change in the class, One way is to define the same struct locally, Is there any other approach we can have to achieve the same result.
}

【问题讨论】:

  • YearValueMethodB 的参数吗?如果是这样,无论您的单元测试如何,您的代码都不会编译(这是错误CS0050)。
  • @PatrickQuirk 感谢您指出这一点,刚刚更新。
  • 我同意@RyanGates,但目前我只是在更新旧的单元测试,它使用的是访问私有方法myLegacyClassPresenter_PrivateAccessor' to PrivateObject`的折旧方法`
  • 这可能是一个错字,但 MethodB 采用 YearValue 但您试图通过 int (YearValue.One) 调用它。我在下面有一个答案,显示了如何传递 YearValue。如果需要传入 int YearValue.One 可以使用反射从答案中获取的类型中获取值

标签: c# unit-testing moq vs-unit-testing-framework


【解决方案1】:

经典示例展示了如果您无法对特定组件进行单元测试,如何重构该组件!

这就是喜欢任何模拟框架强制您执行的操作 - 编写解耦代码。

几件事:

  1. 应该认真重新考虑测试私有方法。你在测试私有方法和属性的那一刻就打破了封装。

  2. 在您的示例中,myLegacyClassPresenter 类与YearValue 结构紧密耦合。您可以使用依赖注入将其解耦。

【讨论】:

  • 正如我所提到的和名称表明 myLegacyClassPresenter 在我的情况下无法更改。
【解决方案2】:

如果你想创建结构的实例,你可以使用类似下面的东西

var theType = Type.GetType("MyNamespace.myLegacyClassPresenter+YearValue");
var parameter = Activator.CreateInstance(theType);

privateobject.Invoke("MethodB", new object[]{parameter});

如果需要传入YearValue.One,那么可以使用Type.GetMember()来获取值。

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 2013-10-20
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2011-10-10
    • 2017-02-06
    相关资源
    最近更新 更多