0

I have an Web API application build in .net core 2.2, I have to write automated test for this application using Xunit. Application involves dependency injection at two level Wep API => Service layer => Repository layer.

Can you suggest ideal approach to write these tests that involves mocking database context?

1 Answer 1

1

A unit test should only ever mock the immediate level of dependencies. For example, if you were testing a controller, you'd mock the service. If you were testing the service, you'd mock the repository, and if you were testing the repository, you'd mock the context (or rather just use the in-memory database if using EF Core).

In other words, you don't build up layers of mocks. The mock should completely abstract the functionality. For the controller example, you'd mock the service to just return some canned value. The service mock would not actually utilize any repository.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Chris! In order to get everything covered, we'll have to mock subsequent layer (whether it is service or repository) and write tests for other layer as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.