简体   繁体   English

Asp.Net Core WebApi:创建单元测试

[英]Asp.Net Core WebApi: Create Unit Tests

I have an AccountController class, here its ctor: 我有一个AccountController类,这里是ctor:

public AccountController(
            UserManager<User> userManager,
            SignInManager<User> signInManager,
            RoleService roleService,
            IConfiguration configuration)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _roleService = roleService;
            _configuration = configuration;
        }

RoleService it's my own class. RoleService是我自己的课程。

I created a xUnit Test project and use Entity Framework Core to avoid mocking and faking database. 我创建了一个xUnit Test项目,并使用Entity Framework Core避免了模拟和伪造数据库。 I use UseInMemoryData method: 我使用UseInMemoryData方法:

var options = new DbContextOptionsBuilder<ApplicationDbContext>()
                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                .Options;
            var context = new ApplicationDbContext(options);

But i do not understand how can i test AccountController, witch injects UserManager<User>, SignInManager<User> and so on. 但是我不明白如何测试AccountController,如何注入UserManager<User>, SignInManager<User>等。 How can i create instance of AccountController class? 如何创建AccountController类的实例?

I normally don't create Unit Test for Controllers, because We need mock a lot of things and it's a hard work. 我通常不创建控制器的单元测试,因为我们需要模拟很多东西,这是一项艰巨的工作。

If you think about that your controller only call another piece of code such as Application Service or a Command Handler you can cover your controller with integration tests, and create Unit Test for your Command Handlers or Application Service or any tier that you have your business logic. 如果您认为控制器仅调用另一段代码,例如应用程序服务或命令处理程序,则可以使用集成测试覆盖控制器,并为命令处理程序或应用程序服务或您具有业务逻辑的任何层创建单元测试。

But maybe if you really want to create a unit test to your controller you will needs create a mock of all dependencies that you need in your controllers using a framework like Moq. 但是,也许如果您真的想为控制器创建单元测试,则需要使用Moq之类的框架来模拟控制器中所需的所有依赖项。

I hope this help :D 我希望这个帮助:D

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

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