简体   繁体   English

C#:具有静态类的DI用于单元测试

[英]C#: DI with static class for unit tests

I have some legacy code that accesses our database. 我有一些旧代码可以访问我们的数据库。 I'd like to create an interface for each one of these classes for IoC/DI in unit testing. 我想为单元测试中的IoC / DI的每个类创建一个接口。

All of the methods in these classes are static. 这些类中的所有方法都是静态的。

When I try to "extract an interface" via VisualStudio, it fails and says, "Could not extract an interface: The type does not contain any member that can be extracted to an interface". 当我尝试通过VisualStudio“提取接口”时,它失败并说:“无法提取接口:该类型不包含任何可以提取到接口的成员”。

There are some links that explain why interfaces shouldn't have static methods here and here . 有一些链接解释了为什么接口在这里这里不应该有静态方法。

This restriction appears to be mostly in support of polymorphism ... which I don't really care about right now and these classes don't really inherit from anything (other than Object). 这种限制似乎主要是在支持多态性……我现在并不真正在乎,这些类实际上并没有从任何对象(对象除外)继承。

So how do I use IoC to get an object I can pull data from? 那么,如何使用IoC获取可以提取数据的对象?

I'd rather not make instance methods since instances increase the working set. 我宁愿不使用实例方法,因为实例会增加工作集。

One technique could be to abstract the static classes away with a wrapper. 一种技术是使用包装器将静态类抽象化。

public MyStaticWrapper : IMyStaticWrapper
{
   public void SomeMethod(string something)
   {
      MyStatic.SomeMethod(something); 
   }
}

Then you can inject the IStaticWrapper where needed. 然后,您可以在需要的地方注入IStaticWrapper


Sorry - just seen this bit.... 抱歉-刚刚看到了这一点...

I'd rather not make instance methods since instances increase the working set. 我宁愿不使用实例方法,因为实例会增加工作集。

Tho I'm not sure if it would meet this requirement, but the footprint of the change is relatively small IMO. 我不确定它是否满足此要求,但是更改的范围相对较小。 Personally I would agree with @DStanleys comment. 我个人同意@DStanleys的评论。

Depending on the goal, you could use something like Microsoft Fakes, in particular shims to intercept the static calls to bring the legacy code under a test harness. 根据目标,您可以使用诸如Microsoft Fakes之类的东西,特别是垫片来拦截静态调用,以将旧代码置于测试工具之下。

Once your library is covered with tests you can have these as a safety net while you introduce proper DI, removing the statics if desired and fully isolated tests. 一旦您的库中包含测试,您就可以在引入适当的DI时将它们作为安全网,并根据需要除去静电并进行完全隔离的测试。

The danger is that shims are evil and can let developers get away with bad practice. 危险是垫片是邪恶的,并且会使开发人员摆脱不良做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM