Asp.Net Core WebApi: Create Unit Tests c# entity-framework-core unit-testing xunit


I have an AccountController class, here its 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.

I created a xUnit Test project and use Entity Framework Core to avoid mocking and faking database. I use UseInMemoryData method:

var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            var context = new ApplicationDbContext(options);

But i do not understand how can i test AccountController, witch injects UserManager<User>, SignInManager<User> and so on. How can i create instance of AccountController class?

5/29/2018 7:49:36 AM

Accepted Answer

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.

I hope this help :D

5/29/2018 7:59:22 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow