Unit Testing Entity Framework Database Update logic with NSubstitute

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.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …