Nikita Goncharuk
Nikita Goncharuk

Reputation: 815

Asp.Net Core WebApi: Create Unit Tests

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>()
                .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. How can i create instance of AccountController class?

Upvotes: 0

Views: 564

Answers (1)

Nicolas Takashi
Nicolas Takashi

Reputation: 1740

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

Upvotes: 2

Related Questions