Unit Testing Entity Framework Database Update logic with NSubstitute
- By : Mydatahack
- Category : .NET, Web Technologies
- Tags: ASP.NET, C#, MySQL, NSubstitute, Unit Test, Web API
In the previous post (UnitTesting ASP.NET Web API by Mocking DbContext with NSubstitute), we explored how to create a unit test for getting data from database with Entity Framework by mocking DbContext and DbSet. We are going to build upon the API we created previously and add PUT logic where it updates the Actor record in MySQL by actor_id.
If you need to brush up on ASP.NET Web API fundamental,check out this post, simpleWeb API in 5 minutes. For the unit testing framework, we are using xUnitand NSubstitute.
Check the complete API and unit testing solutions in our repo here.
Creating PUT logic
To update database, we are going to use EntityState. To make this testable, we will create a MarkAsModified method insakilaContext.cs.
Add it to the interface, IsakilaContext.cs. We also need to add SaveChange() method in the interface. This is to stub SaveChange() method.
Then, add UpdateActor method to ActorsRepository. Check if the id exists in the database. If it does, update the record and return 1.
Controller use this method for PUT request.
Creating Unit Test on Repository
Mocking DbSet and DbContext has been described in the previous post. Now, we can substitute the void method, MarkAsModified and SaveChange() method in the IsakilaContext.
Rest is simple. There are four scenarios in the test. By substituting the void method to increment the counter every time it gets called, we can check how many times MarkAsModified method was called.
Here is the Unit testing best practice guide for further reading.