我正在为以下类遗留类
编写单元测试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.
}
答案 0 :(得分:0)
经典示例,显示如何无法对特定组件进行单元测试,对组件进行REFACTOR!
这就是任何模拟框架强制你做的爱 - 编写解耦代码。
一些事情:
应该认真重新考虑测试私人方法。在测试私有方法和属性时,您会破坏封装。
在您的示例中,myLegacyClassPresenter
类与YearValue
结构紧密耦合。你可以使用依赖注入来解耦它。
答案 1 :(得分:0)
如果要创建结构的实例,可以使用类似下面的内容
var theType = Type.GetType("MyNamespace.myLegacyClassPresenter+YearValue");
var parameter = Activator.CreateInstance(theType);
privateobject.Invoke("MethodB", new object[]{parameter});
如果您需要传递 YearValue.One ,则可以使用theType.GetMember()来获取值。