This is good way to test the application code before it goes for quality assurance (QA). Unit testing ASP.Net Core Web API using XUnit for testing framework and Moq for mocking objects. I'm using AspNet Web Api Client 5.0 and i am trying to unit test a web api controller. May 7, 2019 • Raimund Rittnauer. C#, the web, ASP.NET Core, tutorials, stories, and more! What is unit testing in the first place? Let’s unit test a C# extension method using XUnit’s [Theory] and [InlineData] attributes, so we can write lots of tests in little time! Share in the comments! The Unit test is code where we test all the code paths of the methods and ensure that the results are as expected. From these actions, I see four test scenarios: You may be wondering why scenarios 4 and 5 are listed separately, given that they are expected to return the same type under similar conditions. Here are some things that you should unit test in your Web API controllers: The action returns the correct type of response. And I will introduce a couple of other Nuget packages along the way. Now, let's continue our test-writing spree and work up a bunch of unit tests for the MVC Controller classes in our sample app! So far, our tests have not been noticeably different in practice from when we unit tested the business layer of this app. The MyLogger.cs code is shown below. Using XUnit [Theory] and [InlineData] to Test C# Extension Methods. Let's rename the default test file we got to CartControllerTest.cs.Next, let's discuss our approach. The Moq library can be added to test projects either by package manager or .NET CLI tool. In this video, I will be doing unit testing for the business layer for an ASP.Net Core Web API application. That changes (slightly) when we try to write tests for the TeamController class. In this post I'm going to show you how to use GenFu, Moq and XUnit to create small and isolated unit tests for your ASP.NET Core application. The Unit test is a block of code that helps us in verifying the expected behavior of the other code in isolation; i.e., there is no dependency between the tests. Did you do something similar, and want to let us know about it? How to mock Controller.User ... You need to Mock the ControllerContext, HttpContextBase and finally IPrincipal to mock the user property on Controller. ©2020 C# Corner. c# - mvc - unit testing web api controllers using moq . Using Moq Library to Create Mock Objects While Testing MVC Controllers. This is a good way to test the application code before it goes for quality assurance (QA). Without a mock object, we need to create object of IGetDataRepository which is real. Moq can create a mock version of IGetDataRepository. In unit testing, mock objects are an effective way to control how collaborators outside of the unit being tested should behave for the purposes of the test. Recently I got asked to explain how to unit test a controller that retrieves data using an entity Framework Core DbContext. The wiki gives some ideas about leveraging DI to make testing controllers less of a pain. First, let's look at our LeagueController class. The purpose of this blog post is to get you up and running writing your first unit tests with NUnit and Moq quickly. In the next and final post in this series, we will test a C# extension method using XUnit's [Theory] and [InlineData] attributes, showing how you can run many tests with the same expected outcome in just a few lines of code. Finally, let's consider the PlayerController class: There are two actions in this controller, each with two outcomes that can be tested, for a total of four scenarios. In this article, we will investigate testing your ASP.NET Core 2.0 Web API solutions. In People.SelfHostedApi.Tests project, under the Controllers directory you can find tests for Web API controllers. Writing unit tests for ASP.NET Core MVC Controller is not too different from unit testing other classes, with the main exceptions of setting up the controller class and using Assert.IsAssignableFrom<>() to check the results of actions. In the first step, we will have to create test data for testing, using a mock or stub object. There was an error sending the email, please try again, Check your inbox and click the link to confirm your subscription. So when we write unit tests, we do not execute them on the actual class instances, but instead perform in-memory unit testing by making a proxy of class objects. We can create a base class with a default mock of the service, which nearby all unit tests are using and modify where needed. There's only one action here, Index(), so we only need to consider the test cases for that action. Note that in this scenario we want to confirm that _playerService.GetForLeague() was never called. The Moq framework provides an easy mechanism to mock the dependencies which makes it easier to test classes having constructor injection. It is possible to check if the redirected action is the action that we expect, and this is how to do it. In this project is nothing special, except the new PersonsController, which is using a PersonService: The Personclass is created in a new folder "Models" and is a simple POCO: The PersonServiceuses GenFu to auto generate a list of Persons: This Service needs to be regist… I am unit testing that the URL that I give to my IRestClient is valid. RESTful Day #8: Unit Testing and Integration Testing in WebAPI using NUnit and Moq framework (Part 2). This is the preferred way to check for the type of IActionResult that is normally returned from ASP.NET Core MVC Controller classes. For this part, I created a simple Logger called MyLogger with just a Log method to demonstrate unit testing. EFMVC is a simple app, developed as a reference implementation for demonstrating ASP.NET MVC, EF Code First, ASP.NET Web API, Domain-Driven Design (DDD), Test-Driven Development (DDD). It begins by defining what a „unit“ is and although this is not strictly defined, unit represents a unit of work – usually a single method in our code.We test these units individually, making sure that each of them is doing exactly that what it is written for.Nothing more, nothing less.What is important to understand is that we are not testing the behavior of the dependencies of that method. Using this fake object, we can isolate the code which is making an external call. In this example, I am using Setup and Returns methods to create a mock object. c# - with - unit testing web api controllers using moq . Let's list them: Now, we can write the unit tests for these scenarios. What is Integration Test. All contents are copyright of their authors. The answer is "no". See a way I can improve the above unit tests? Let's continue our unit test extravaganza by writing a set of unit tests for our ASP.NET Core MVC Controllers! Here, to create controller class instance, we require the object of IGetDataRepository. RESTful Day #7: Unit Testing and Integration Testing in WebAPI using NUnit and Moq framework (Part1). We've already seen why and where we want to write unit tests, how to use Moq to create fluent mocked classes to make our tests more readable, and even how to unit test the business layer of our sample app. MOQ can be downloaded using a NuGet Package. To demonstrate the code, I am using MSTest framework. why and where we want to write unit tests, how to unit test the business layer of our sample app. Testing is the most important process for any software application. So lets get started. As you unit test your controller actions, make sure you focus only on their behavior. If the response includes a domain model, verify the model type. views, json, http status code, etc. It means that the above test will work with. The primary reason is that in Scenario 5, the method _teamService.Search() is expected to be called, whereas in Scenario 4, it will not be. Don't forget to check out the sample project over on GitHub! Unit testing involves testing a part of an application in isolation from its infrastructure and dependencies. If you want to learn unit testing in depth using mocking frameworks such as Moq, FakeItEasy and Typemock Isolator, I highly recommend checking out The Art of Unit Testing: with examples in C# by Roy Osherove.