Ava*_*ais 3 c# oop inheritance dependency-injection
我有以下场景:
我想模拟一个界面,以便可以对我的应用程序进行单元测试。我试图不创建一个新的模拟类来实现我的接口,而是创建一个继承原始具体类的新类,并在调用该方法时使用 new 关键字强制新的行为。但由于某种原因,正在调用具体类的方法,而不是我创建的类(作为模拟)
以下代码:
public interface IMyService
{
Model GetModelData(int id)
}
public class MyService : IMyService
{
public Model GetModelData(int id)
{
//call to db
}
}
public class MyService2 : MyService
{
public MyService2()
: base(new MyRepository())
{
}
public new Model GetModelData(int id)
{
return new Model();
}
}
Run Code Online (Sandbox Code Playgroud)
注入依赖:
x.ForRequestedType<IMyService>().TheDefaultIsConcreteType<MyService2>();
Run Code Online (Sandbox Code Playgroud)
检索具体类:在调试时,我可以看到 myService 指向 MyService2 类,但该方法在 MyService 类上执行。
_myServie = ObjectFactory.GetInstance<IMyService>();
Model modelData = _myServie.GetModelData(5);
Run Code Online (Sandbox Code Playgroud)
仅使用new创建一个新方法而不将其与接口关联。您在实际代码中使用该接口(我假设),因此您希望将接口方法绑定到新方法。为此,您必须声明您正在再次实现该接口。下面是一个显示差异的示例:
using System;
interface IFoo
{
void Bar();
}
class Normal : IFoo
{
public void Bar()
{
Console.WriteLine("Normal.Bar");
}
}
class Extended1 : Normal
{
public new void Bar()
{
Console.WriteLine("Extended1.Bar");
}
}
class Extended2 : Normal, IFoo
{
public new void Bar()
{
Console.WriteLine("Extended2.Bar");
}
}
class Test
{
static void Main()
{
IFoo x = new Extended1();
IFoo y = new Extended2();
x.Bar();
y.Bar();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Normal.Bar
Extended2.Bar
Run Code Online (Sandbox Code Playgroud)
因此,如果您将类声明更改为:
public class MyService2 : MyService, IMyService
Run Code Online (Sandbox Code Playgroud)
你应该会发现它确实有效。请注意,我不能说我是这种方法的忠实粉丝 -MyService调用该方法的任何内容都将调用其自己的实现,除非它碰巧通过IMyService-type 引用进行调用。您可以将具体类中的接口实现设为虚拟,然后在子类中重写它;这在某些方面会更好,但在另一些方面会更糟。基本上,这种“半继承”对我来说感觉相当脆弱。
我怀疑如果你有一个抽象基类,你的实际实现和测试实现都派生自......,它会更干净。
| 归档时间: |
|
| 查看次数: |
391 次 |
| 最近记录: |