banner



How To Write Unit Test Case For Ef Core Entity Data Layer In C#

This commodity volition demonstrate how to write Unit Exam Cases for Crud operations in ASP.Internet Core Web API with xUnit projection. In this demonstration, we will write the Unit Test Cases for CRUD (CREATE, READ, UPDATE and DELETE) operations. Nosotros will write at least three different Unit Test Cases for 3 dissimilar scenarios. In this demonstration, we will not implement Crud operation in ASP.Cyberspace Cadre Web API because we accept already written 1 commodity on this previously. We accept used that lawmaking which we take written for the previous commodity. If you are willing to learn how to perform CRUD operations in ASP.Cyberspace Cadre Web API using Entity Framework Core, you tin can visit here.

If yous are willing to download the code for above article, you tin can download it from GitHub here.

We are writing this article because we haven't got much information about how to write Unit Test Instance for Crud Operations on the internet with step by step information. And then, we have decided to write on this topic and then that information technology tin can aid others. Without wasting much time on an introduction, let's move to the practical sit-in of how to write Grime operations Unit Exam Cases for ASP.NET Core Web API project.

First, let's download the projection from GitHub as provided in the  link above and open it in Visual Studio (We are using Visual Studio 2017 for this demonstration). Once the project opens, move to the Models folder and open the Post Model and let'southward modify the existing project "CoreServies" Postal service entity and make Championship column as a required field and ascertain the length of the field as follows. We are modifying this Mail service entity because nosotros volition use it while writing the Unit Test Cases for "Create" and "Update" operations.

  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.ComponentModel.DataAnnotations.Schema;
  4. namespace CoreServices.Models
  5. {
  6. public  partial class  Postal service
  7.     {
  8. public int  PostId { get; set up; }
  9.         [Column(TypeName ="varchar(20)" )]
  10.         [Required]
  11. public  cord Title { get; set; }
  12. public  cord Clarification { get; set; }
  13. public int ? CategoryId { get; set; }
  14. public  DateTime? CreatedDate { go; set up; }
  15. public  Category Category { go; set; }
  16.     }
  17. }

Let's build the CoreServices project and see if everything is fine or not. In one case all are green then we tin can motility ahead.

Now, we will create ane Test projection where we will write the Unit Examination Cases. And then, right-click on the solution of "CoreServices" projection and choose Add and so choose "New Projection".

CRUD Operations Unit Testing In ASP.NET Core Web API With xUnit

The next screen will provide lots of options to add a new project, only you take to move ".Net Cadre" inside the Installed template and then choose "xUnit Test Project (.Cyberspace Cadre)" as you can see with the post-obit image. Only provide the suitable name as per standard, information technology should exist "Project proper name with Test" (CoreServices.Examination) and click to OK.

CRUD Operations Unit Testing In ASP.NET Core Web API With xUnit

At present, we accept the Exam Project prepare. Let'southward motility and add together the references of the Main project (CoreServices) where we take written actual Controller, Repository and Model Classes. Because while writing the Unit Test Cases, we volition use these existing Controller, Repository, Model and DbContext instances.

For calculation the project reference, right click on the "Dependencies" of "CoreServices.Exam" projection and choose "Add References" and then choose "CoreServices" projection from the Projection > Solution as shown with the following image and click to OK.

CRUD Operations Unit Testing In ASP.NET Core Web API With xUnit

Now, we take added the reference of "CoreServices" project within the "CoreServices.Exam" projection. After this signal, nosotros tin can access the components which are defined in "CoreServices" project. Actually, we are only willing to employ Controller and Repository for writing Unit Test Cases, but we will not use the Actual DB.

For testing purposes, we will create i separate Examination DB (BlogDB) with the same name on a different server or with some other proper name on the same server. For this sit-in, we are using the same database name with another server.

Once the database is ready, nosotros have to seed some data into a database before performing testing. So, for that, we volition create 1 form which will be responsible for creating some dummy data which we will utilise further while running Exam Cases.

So, let'southward create a class as "DummyDataDBInitializer" with a "Seed" method, which will kickoff delete your all database tables every time and regenerate tables based on your Model configurations and add some dummy data. You tin can go assistance with following code snippets. Here yous tin see we are adding some data for "Category" and "Post" tables and then committing information technology using "context.SaveChanges()" method.

  1. using CoreServices.Models;
  2. using System;
  3. namespace CoreServices.Examination
  4. {
  5. public class  DummyDataDBInitializer
  6.     {
  7. public  DummyDataDBInitializer()
  8.         {
  9.         }
  10. public void  Seed(BlogDBContext context)
  11.         {
  12.             context.Database.EnsureDeleted();
  13.             context.Database.EnsureCreated();
  14.             context.Category.AddRange(
  15. new  Category() { Name = "CSHARP" , Slug = "csharp"  },
  16. new  Category() { Name = "VISUAL STUDIO" , Slug = "visualstudio"  },
  17. new  Category() { Name = "ASP.Net Cadre" , Slug = "aspnetcore"  },
  18. new  Category() { Name = "SQL SERVER" , Slug = "sqlserver"  }
  19.             );
  20.             context.Post.AddRange(
  21. new  Mail service() { Title = "Test Title 1" , Description = "Test Description 1" , CategoryId = 2, CreatedDate = DateTime.Now },
  22. new  Mail() { Title = "Test Title ii" , Description = "Test Description ii" , CategoryId = 3, CreatedDate = DateTime.At present }
  23.             );
  24.             context.SaveChanges();
  25.         }
  26.     }
  27. }

In this demonstration, we will use "Fluent Assertions" for writing a beautiful and user-friendly Unit Test Case.

Fluent Assertions is a very extensive gear up of extension methods that allows you to more naturally specify the expected outcome of a TDD or BDD-style unit tests. Targets .Internet Framework iv.five and four.7, also as .Cyberspace Core 2.0, .NET Standard ane.3, one.6 and 2.0.

So, allow'southward open NuGet Package Manager for "CoreServies.Test" project and browse for "FluentAssertions" and installed it.

CRUD Operations Unit Testing In ASP.NET Core Web API With xUnit

Now, it'due south fourth dimension to create a class where we volition write the actual Unit Test Cases. And so, let'due south create one class as "PostUnitTestController.cs" in "CoreServices.Test" as follows.

CRUD Operations Unit Testing In ASP.NET Core Web API With xUnit

One time PostUnitTestController form will exist ready, first nosotros will try to access our database where at the runtime, we will seed some dummy information and access the dummy data for testing. So, let's ready the connection string and based on that become the example of "BlogDBContext".

Notation
Here connection string is defined within the grade, that is not a good approach simply we are using information technology only for this demonstration, but you can use some configuration files to go along this information and admission this connection string from that configuration file.

  1. public class  PostUnitTestController
  2. {
  3. individual  PostRepository repository;
  4. public static  DbContextOptions<BlogDBContext> dbContextOptions { become; }
  5. public static  cord connectionString = "Server=ABCD;Database=BlogDB;UID=sa;PWD=xxxxxxxxxx;" ;
  6. static  PostUnitTestController()
  7.         {
  8.             dbContextOptions =new  DbContextOptionsBuilder<BlogDBContext>()
  9.                 .UseSqlServer(connectionString)
  10.                 .Options;
  11.         }

One time nosotros accept available the instance of the "BlogDBContext" then nosotros will go to get the case of the actual repository "PostRepository" based on the instance of "BlogDBContext" equally follows inside the "PostUnitTestControler" constructor.

  1. public  PostUnitTestController()
  2. {
  3. var  context = new  BlogDBContext(dbContextOptions);
  4.     DummyDataDBInitializer db =new  DummyDataDBInitializer();
  5.     db.Seed(context);
  6.     repository =new  PostRepository(context);
  7. }

Now, nosotros accept everything similar connectedness string, an example of BlogDBContext, an instance of PostRepository and all. So, we can move next and write Unit Test Cases for all EndPoints which are defined within the PostController in "CoreServices" projection.

We will write the Unit Test Cases one by one for all the EndPoints. If y'all are new in Unit Testing and willing to write it then you can go with my article "Getting started with Unit of measurement Testing using C# and xUnit" where y'all will larn more about Unit Testing Pros and Cons and the best style to write Unit Test Cases.

We need to go on three things while writing the Unit Test Cases and these are Arranging the data, Performing the action and Matching the output (Arrange, Act, Assert).

And so, let's starting time write Unit Test Case for "Get By Id " method as follows. We have multiple Unit Test Cases to test a single method. Each Unit Test Case has it's own responsibility similar matching the OK Result, checking for Not Found Effect, checking for Bad Requests etc.

When we talk about Fluent Assertions, we are implementing in "Task_GetPostById_MatchResult" for getting the actual information.

  1. #region Get By Id
  2.         [Fact]
  3. public  async void  Task_GetPostById_Return_OkResult()
  4.         {
  5. var  controller = new  PostController(repository);
  6. var  postId = 2;
  7. var  information = look controller.GetPost(postId);
  8.             Affirm.IsType<OkObjectResult>(data);
  9.         }
  10.         [Fact]
  11. public  async void  Task_GetPostById_Return_NotFoundResult()
  12.         {
  13. var  controller = new  PostController(repository);
  14. var  postId = 3;
  15. var  information = await controller.GetPost(postId);
  16.             Affirm.IsType<NotFoundResult>(information);
  17.         }
  18.         [Fact]
  19. public  async void  Task_GetPostById_Return_BadRequestResult()
  20.         {
  21. var  controller = new  PostController(repository);
  22. int ? postId = null ;
  23. var  information = expect controller.GetPost(postId);
  24.             Assert.IsType<BadRequestResult>(data);
  25.         }
  26.         [Fact]
  27. public  async void  Task_GetPostById_MatchResult()
  28.         {
  29. var  controller = new  PostController(repository);
  30. int ? postId = 1;
  31. var  data = await controller.GetPost(postId);
  32.             Assert.IsType<OkObjectResult>(data);
  33. var  okResult = data.Should().BeOfType<OkObjectResult>().Discipline;
  34. var  post = okResult.Value.Should().BeAssignableTo<PostViewModel>().Subject;
  35.             Assert.Equal("Test Title 1" , mail.Championship);
  36.             Affirm.Equal("Exam Clarification ane" , post.Clarification);
  37.         }

0 Response to "How To Write Unit Test Case For Ef Core Entity Data Layer In C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel