C#:使用实现私有接口的对象参数测试方法
C#: test a method with an object parameter implementing a private interface
我的第一个项目的方法是 returns 一个 Model 对象实例,它是用私有 class PrivateModel 继承 Model 和一个私有接口 IFoo 实现的。
样本:
项目 1:
public class Model {}
private interface IFoo {}
private class PrivateModel : Model, IFoo {}
// a sample class with the returning method
public class Bar
{
public static Model CreateModelInstance()
{ return new PrivateModel(); }
// code...
}
项目 2:
// get model instance
var model = Bar.CreateModelInstance(); // return a Model
第二个项目使用模型参数调用方法"Act",但 Act 的实现测试模型是否为 PrivateModel(使用 IFoo 实现)。
项目 1:
public class Bar
{
// code...
public static bool Act(Model model)
{
// sample logic
return model is IFoo;
}
}
现在问题:
因为我必须测试一个调用 Act 方法的方法(它是静态的),而且我不能修改它,所以我必须构建一个实现 IFoo 的对象(即私有的)。我能否在测试项目(第三个项目)中实现类似于 TestClass: IFoo
的 class,或者我必须使用从 Project1 返回的模型?
您不能在 assembly/class 接口定义之外实现私有接口。
要么重新设计代码以使其更易于测试,要么使用从 Project1 返回的模型(或任何创建实现正确接口的模型)。
您的案例实际上可能是私有接口有用的罕见案例之一 - 当您出于某种原因无法密封实现 类 时,请确保非常严格的对象创建规则。是否对您的案例有用-您来电。
我的第一个项目的方法是 returns 一个 Model 对象实例,它是用私有 class PrivateModel 继承 Model 和一个私有接口 IFoo 实现的。
样本:
项目 1:
public class Model {}
private interface IFoo {}
private class PrivateModel : Model, IFoo {}
// a sample class with the returning method
public class Bar
{
public static Model CreateModelInstance()
{ return new PrivateModel(); }
// code...
}
项目 2:
// get model instance
var model = Bar.CreateModelInstance(); // return a Model
第二个项目使用模型参数调用方法"Act",但 Act 的实现测试模型是否为 PrivateModel(使用 IFoo 实现)。
项目 1:
public class Bar
{
// code...
public static bool Act(Model model)
{
// sample logic
return model is IFoo;
}
}
现在问题:
因为我必须测试一个调用 Act 方法的方法(它是静态的),而且我不能修改它,所以我必须构建一个实现 IFoo 的对象(即私有的)。我能否在测试项目(第三个项目)中实现类似于 TestClass: IFoo
的 class,或者我必须使用从 Project1 返回的模型?
您不能在 assembly/class 接口定义之外实现私有接口。
要么重新设计代码以使其更易于测试,要么使用从 Project1 返回的模型(或任何创建实现正确接口的模型)。
您的案例实际上可能是私有接口有用的罕见案例之一 - 当您出于某种原因无法密封实现 类 时,请确保非常严格的对象创建规则。是否对您的案例有用-您来电。