简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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