loserssaywhatwhat
loserssaywhatwhat

Reputation: 1

Should unit tests in Test Explorer connect to a database?

Should unit tests in Test Explorer connect to a database?

I can execute the same code outside of the test case and it correctly inserts into the database. When trying to test the repository (that performs the insert) within a unit test written in Visual Studio test explorer, the insert does not happen.

Upvotes: 0

Views: 252

Answers (1)

Shyju
Shyju

Reputation: 218962

Unit tests are supposed to test your business layer logic/methods. It should not be inserting to the database. You should be using a fake data access layer( Use a mocking library like Moq / FakeItEasy) if needed.

A quick example using Moq library.

var repoMoq = new Mock<IRepository>();
repoMoq.Setup(s=>s.GetStudentName(It.IsAny<int>)).Returns("Test Student");
var bl = new StudentManagementBusinessLayerClass(repoMoq.Object);
// To do : Assert Something now.
// Ex : bl.GetStudent(234);

Here you are mocking your Data access layer,IRepository's GetStudentMethod to return "TestStudent" when it is being called from the Unit test.

End to end Integration tests are the one you need where you execute a full cycle which inserts data to db and once your testing is done, Delete /Rollback the test data.

Upvotes: 2

Related Questions