简体   繁体   English

Unity,单元测试和ASP.NET(非MVC)

[英]Unity, Unit tests and ASP.NET (not MVC)

I am using Unity in an ASP.NET project (not MVC). 我在ASP.NET项目(不是MVC)中使用Unity。 It seems that the Unit Tests need to be aware of Unity, create an IoC container and insert Mocks into that, unlike the other unit testing frameworks I have used. 看起来单元测试需要了解Unity,创建一个IoC容器并将Mocks插入其中,这与我使用的其他单元测试框架不同。

The examples of resolving classes using Unity seems to be either: 使用Unity解析类的示例似乎是:

public class Foo
{

    [Dependency]
    private ILogger Logger { set; get; }

}

or resolving directly from the container: 或直接从容器中解析:

UnityTest.Interfaces.IMenuBL ser = Global.Container.Resolve<UnityTest.Interfaces.IMenuBL>(); 

Is it possible, in non-MVC ASP.NET to have Unity perform constructor injection so that my unit tests aren't tied to my IoC container? 在非MVC ASP.NET中,是否可以让Unity执行构造函数注入,以使我的单元测试不绑定到我的IoC容器?

Cheers 干杯

Dave 戴夫

ASP.NET Web Forms weren't designed with testability in mind. ASP.NET Web窗体在设计时并未考虑可测试性。 You can't do constructor injection with Web Forms, at least not without using some dodgy workarounds like creating a page handler - see How to use Dependency Injection with ASP.NET Web Forms . 您不能使用Web Forms进行构造函数注入,至少不能不使用诸如创建页面处理程序之类的一些变通方法-请参阅如何将依赖注入与ASP.NET Web Forms一起使用

The best option is to use property injection. 最好的选择是使用属性注入。

Edit: you may consider using the MVP pattern in order to improve the testability of your Web Forms pages: 编辑:您可以考虑使用MVP模式以提高Web窗体页面的可测试性:

MSDN - Better Web Forms with the MVP Pattern MSDN-使用MVP模式的更好的Web表单

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

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