RESTful Day #8: Unit Testing and Integration Testing in WebAPI using NUnit and Moq framework (Part2)


Download Source Code

Introduction

In my last article I explained how to write unit tests for business service layer. In this article we’ll learn on how to write unit tests for WebAPI controllers i.e. REST’s actual endpoints. I’ll use NUnit and Moq framework to write test cases for controller methods. I have already explained about installing NUnit and configuring unit tests. My last article also covered explaining about NUnit attributes used in writing unit tests. Please go through my last article of the series before following this article.

Roadmap

Following is the roadmap I have setup to learn WebAPI step by step,

I’ll purposely use Visual Studio 2010 and .net Framework 4.0 because there are few implementations that are very hard to find in .Net Framework 4.0, but I’ll make it easy by showing how we can do it.

Setup Solution

When you take the code base from my last article and open it in visual studio, you’ll see the project structure something like as shown in below image,

image

The solution contains the WebAPI application and related projects. There are two newly added projects named BusinessServices.Tests and TestHelper. We’ll use TestHelper project and its classes for writing WebAPI unit tests in the same way we used it for writing business services unit tests.

Testing WebAPI

Step 1: Test Project

Add a simple class library in the existing visual studio and name it ApiController.Tests. Open Tools->Library Packet Manager->Packet manager Console to open the package manager console window. We need to install same packages as we did for business services before we proceed.

image

Step 2: Install NUnit package

In package manager console, select ApiController.Tests as default project and write command “Install-Package NUnit –Version 2.6.4”. When you run the command, it says NUnit is already installed, that’s because we installed this package for BusinessServices.Tests project, but doing this again for a new project (in our case it is ApiController.Tests) will not install it again but add a reference to nunit framework library and mark an entry in packages.config for ApiController.Tests project.

image

After successfully installed, you can see the dll reference in project references i.e. nunit.framework,

Step 3: Install Moq framework

Install the framework on the same project in the similar way as explained in Step 2. Write command “Install-Package Moq”.

image

Step 4: Install Entity Framework

Install-Package EntityFramework –Version 5.0.0

image

Step 5: Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET. We’ll use it for serializing/de-serializing request and responses.

Install-Package Newtonsoft.Json -Version 4.5.11

image

Our packages.config i.e. automatically added in the project looks like,

   1:

   2: <?xml version="1.0" encoding="utf-8"?>

   3: <packages>

   4: <package id="EntityFramework" version="5.0.0"

   5: targetFramework="net40" />

   6: <package id="Moq" version="4.2.1510.2205"

   7: targetFramework="net40" />

   8: <package id="Newtonsoft.Json" version="4.5.11"

   9: targetFramework="net40" />

  10: <package id="NUnit" version="2.6.4"

  11: targetFramework="net40" />

  12: </packages>

Step 6: References

Add references of BusinessEntities, BusinessServices, DataModel, TestsHelper, WebApi project to this project.

image

ProductController Tests

We’ll start with setting up the project and setting up the pre-requisites for tests and gradually move on to actual tests.

Tests Setup

Add a new class named ProductControllerTest.cs in ApiController.Tests project.

Declare variables

Define the private variables that we’ll use in the class to write tests,

   1:

   2: #region Variables

   3: private IProductServices _productService;

   4: private ITokenServices _tokenService;

   5: private IUnitOfWork _unitOfWork;

   6: private List<Product> _products;

   7: private List<Token> _tokens;

   8: private GenericRepository<Product>

   9: _productRepository;

  10: private GenericRepository<Token>

  11: _tokenRepository;

  12: private WebApiDbEntities _dbEntities;

  13: private HttpClient _client;

  14: private HttpResponseMessage _response;

  15: private string _token;

  16: private const string ServiceBaseURL =

  17: "http://localhost:50875/";

  18: #endregion

 

Variable declarations are self-explanatory where _productService will hold mock for ProductServices, _tokenService will hold mock for TokenServices, _unitOfWork for UnitOfWork class, _products will hold dummy products from DataInitializer class of TestHelper project, __tokens will hold dummy tokens from DataInitializer class of TestHelper project ,_productRepository , tokenRepository and _dbEntities holds mock for Product Repository , Token Repository and WebAPIDbEntities from DataModel project respectively.

Since WebAPI is supposed to return response in HttpResponse format so _response is declared to store the returned response against which we can assert._token holds the token value after successful authentication._client and ServiceBaseURL may not be required in this article’s context, but you can use them to write integration tests that purposely uses actual API URL’s and test on actual database.

Write Test Fixture Setup

Write test fixture setup method with [TestFixtureSetUp] attribute at the top, this method runs only one time when tests are executed.

   1:

   2: [TestFixtureSetUp]

   3: public void Setup()

   4: {

   5: _products = SetUpProducts();

   6: _tokens = SetUpTokens();

   7: _dbEntities = new

   8: Mock<WebApiDbEntities>().Object;

   9: _tokenRepository = SetUpTokenRepository();

  10: _productRepository = SetUpProductRepository();

  11: var unitOfWork = new Mock<IUnitOfWork>();

  12: unitOfWork.SetupGet(s =>

  13: s.ProductRepository).Returns(_productRepository);

  14: unitOfWork.SetupGet(s =>

  15: s.TokenRepository).Returns(_tokenRepository);

  16: _unitOfWork = unitOfWork.Object;

  17: _productService = new

  18: ProductServices(_unitOfWork);

  19: _tokenService = new TokenServices(_unitOfWork);

  20: _client = new HttpClient { BaseAddress = new

  21: Uri(ServiceBaseURL) };

  22: var tokenEntity = _tokenService.GenerateToken(1);

  23: _token = tokenEntity.AuthToken;

  24: _client.DefaultRequestHeaders.Add("Token",

  25: _token);

  26: }

The purpose of this method is similar to that of method we wrote for business services.here SetupProducts() will fetch the list of dummy products and SetupTokens() will get the list of dummy tokens.We try to setup mock for Token and Product repository as well, and after that mock UnitOfWork and set it up against already mocked token and product repository._prdouctService and _tokenService are the instances of ProductService and TokenService respectively, both initialized with mocked Unit of Work.

Following is the line of code that I would like to explain more,

   1:

   2: var tokenEntity = _tokenService.GenerateToken(1);

   3: _token = tokenEntity.AuthToken;

   4: _client.DefaultRequestHeaders.Add("Token",

   5: _token);

 

In the above code we are initializing the _client i.e. HttpClient with Token value in request header. We are doing this because, if you remember about the security (Authentication and Authorization) we implemented in Product Controller, which says no request will be entertained unless it is authorized i.e. contains an authentication token in its header.So here we generate the token via TokenService’s GenerateToken() method, passing a default used id as “1”, and use that token for authorization. We require this only to perform integration testing as for unit tests we would directly be calling controller methods from our unit tests methods, but for actual integration tests you’ll have to mock all pre-conditions before calling an API endpoint.

SetUpProducts():

   1:

   2: private static List<Product> SetUpProducts()

   3: {

   4: var prodId = new int();

   5: var products = DataInitializer.GetAllProducts();

   6: foreach (Product prod in products)

   7: prod.ProductId = ++prodId;

   8: return products;

   9: }

SetUpTokens():

   1:

   2: private static List<Token> SetUpTokens()

   3: {

   4: var tokId = new int();

   5: var tokens = DataInitializer.GetAllTokens();

   6: foreach (Token tok in tokens)

   7: tok.TokenId = ++tokId;

   8: return tokens;

   9: }

Write Test Fixture Tear Down

 

Unlike [TestFixtureTearDown] tear down is used to de-allocate or dispose the objects.

Following is the code for teardown.

   1:

   2: [TestFixtureTearDown]

   3: public void DisposeAllObjects()

   4: {

   5: _tokenService = null;

   6: _productService = null;

   7: _unitOfWork = null;

   8: _tokenRepository = null;

   9: _productRepository = null;

  10: _tokens = null;

  11: _products = null;

  12: if (_response != null)

  13: _response.Dispose();

  14: if (_client != null)

  15: _client.Dispose();

  16: }

Write Test Setup

In this case Setup is only required if you write integration test. So you can choose to omit this.

   1:

   2: [SetUp]

   3: public void ReInitializeTest()

   4: {

   5: _client = new HttpClient { BaseAddress = new

   6: Uri(ServiceBaseURL) };

   7: _client.DefaultRequestHeaders.Add("Token",

   8: _token);

   9: }

Write Test Tear down

Test [TearDown] is invoked after every test execution is complete.

   1:

   2: [TearDown]

   3: public void DisposeTest()

   4: {

   5: if (_response != null)

   6: _response.Dispose();

   7: if (_client != null)

   8: _client.Dispose();

   9: }

Mocking Repository

I have created a method SetUpProductRepository() to mock Product Repository and assign it to _productrepository in ReInitializeTest() method and SetUpTokenRepository() to mock TokenRepository and assign that to _tokenRepository in ReInitializeTest() method.

SetUpProductRepository():

   1:

   2: private GenericRepository<Product>

   3: SetUpProductRepository()

   4: {

   5: // Initialise repository

   6: var mockRepo = new

   7: Mock<GenericRepository<Product>>(MockBehavior.Default,

   8: _dbEntities);

   9: // Setup mocking behavior

  10: mockRepo.Setup(p =>

  11: p.GetAll()).Returns(_products);

  12: mockRepo.Setup(p =>

  13: p.GetByID(It.IsAny<int>()))

  14: .Returns(new Func<int, Product>(

  15: id => _products.Find(p =>

  16: p.ProductId.Equals(id))));

  17: mockRepo.Setup(p =>

  18: p.Insert((It.IsAny<Product>())))

  19: .Callback(new Action<Product>(newProduct

  20: =>

  21: {

  22: dynamic maxProductID = _products.Last().ProductId;

  23: dynamic nextProductID = maxProductID + 1;

  24: newProduct.ProductId = nextProductID;

  25: _products.Add(newProduct);

  26: }));

  27: mockRepo.Setup(p =>

  28: p.Update(It.IsAny<Product>()))

  29: .Callback(new Action<Product>(prod =>

  30: {

  31: var oldProduct = _products.Find(a => a.ProductId ==

  32: prod.ProductId);

  33: oldProduct = prod;

  34: }));

  35: mockRepo.Setup(p =>

  36: p.Delete(It.IsAny<Product>()))

  37: .Callback(new Action<Product>(prod =>

  38: {

  39: var productToRemove =

  40: _products.Find(a => a.ProductId ==

  41: prod.ProductId);

  42: if (productToRemove != null)

  43: _products.Remove(productToRemove);

  44: }));

  45: // Return mock implementation object

  46: return mockRepo.Object;

  47: }

SetUpTokenRepository():

   1:

   2: private GenericRepository<Token>

   3: SetUpTokenRepository()

   4: {

   5: // Initialise repository

   6: var mockRepo = new

   7: Mock<GenericRepository<Token>>(MockBehavior.Default,

   8: _dbEntities);

   9: // Setup mocking behavior

  10: mockRepo.Setup(p =>

  11: p.GetAll()).Returns(_tokens);

  12: mockRepo.Setup(p =>

  13: p.GetByID(It.IsAny<int>()))

  14: .Returns(new Func<int, Token>(

  15: id => _tokens.Find(p =>

  16: p.TokenId.Equals(id))));

  17: mockRepo.Setup(p =>

  18: p.Insert((It.IsAny<Token>())))

  19: .Callback(new Action<Token>(newToken =>

  20: {

  21: dynamic maxTokenID = _tokens.Last().TokenId;

  22: dynamic nextTokenID = maxTokenID + 1;

  23: newToken.TokenId = nextTokenID;

  24: _tokens.Add(newToken);

  25: }));

  26: mockRepo.Setup(p =>

  27: p.Update(It.IsAny<Token>()))

  28: .Callback(new Action<Token>(token =>

  29: {

  30: var oldToken = _tokens.Find(a => a.TokenId ==

  31: token.TokenId);

  32: oldToken = token;

  33: }));

  34: mockRepo.Setup(p =>

  35: p.Delete(It.IsAny<Token>()))

  36: .Callback(new Action<Token>(prod =>

  37: {

  38: var tokenToRemove =

  39: _tokens.Find(a => a.TokenId == prod.TokenId);

  40: if (tokenToRemove != null)

  41: _tokens.Remove(tokenToRemove);

  42: }));

  43: // Return mock implementation object

  44: return mockRepo.Object;

  45: }

 

Unit Tests

image

All set now and we are ready to write unit tests for ProductController. We’ll write test to perform all the CRUD operations and all the action exit points that are part of ProductController.

1. GetAllProductsTest ()

Our ProductService in BusinessServices project contains a method named GetAllProducts (), following is the implementation,

   1:

   2: [Test]

   3: public void GetAllProductsTest()

   4: {

   5: var productController = new

   6: ProductController(_productService)

   7: {

   8: Request = new HttpRequestMessage

   9: {

  10: Method = HttpMethod.Get,

  11: RequestUri = new Uri(ServiceBaseURL +

  12: "v1/Products/Product/all")

  13: }

  14: };

  15: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  16: new HttpConfiguration());

  17: _response = productController.Get();

  18: var responseResult =

  19: JsonConvert.DeserializeObject<List<Product>>(_response.Content.ReadAsStringAsync().Result);

  20: Assert.AreEqual(_response.StatusCode,

  21: HttpStatusCode.OK);

  22: Assert.AreEqual(responseResult.Any(), true);

  23: var comparer = new ProductComparer();

  24: CollectionAssert.AreEqual(

  25: responseResult.OrderBy(product => product,

  26: comparer),

  27: _products.OrderBy(product => product, comparer),

  28: comparer);

  29: }

Let me explain the code step by step. We start code by creating an instance of ProductController and initialize the Request property of controller with new request message stating calling http method as GET and initialize the RequestUri with base hosted service URL and appended with actual end point of the method. Initializing RequestUri is not necessary in this case but will help you if you test actual service end point. In this case we are not testing actual endpoint but the direct controller method.

HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() line adds default httpconfiguration to HttpConfigurationKey necessary for controller instance instantiation.

_response = productController.Get(); line calls the Get() method of controller that fetches all the products from dummy _products list. Since the return type of the method was an http response message, we need to parse it to get the JSON result sent from the method. All the transactions from API’s should ideally happen in form of JSON or XML only. This helps client to understand the response and its result set. We de-serialize the object we got from _response using NewtonSoft library into a list of products. That means the JSON response is converted to List<Product> for better accessibility and comparison. Once done with JSON to List object conversion, I have put three asserts to test the result.

Assert.AreEqual(_response.StatusCode, HttpStatusCode.OK); line checks the http status code of the response, the expected is HttpStatusCode.OK.

Second assert i.e. Assert.AreEqual(responseResult.Any(), true); checks that we have got the items in the list or not. Third assert is the actual confirmation assert for our test that compares each product from the actual product list to the returned product list.

image

We got both the list, and we need to check the comparison of the lists, I just pressed F5 and got the result on TestUI as,

image

This shows our test is passed, i.e. the expected and returned result is same.

2. GetProductByIdTest ()

This unit test verifies if the correct result is returned if we try to invoke GetProductById() method of product controller.

   1:

   2: [Test]

   3: public void GetProductByIdTest()

   4: {

   5: var productController = new

   6: ProductController(_productService)

   7: {

   8: Request = new HttpRequestMessage

   9: {

  10: Method = HttpMethod.Get,

  11: RequestUri = new Uri(ServiceBaseURL +

  12: "v1/Products/Product/productid/2")

  13: }

  14: };

  15: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  16: new HttpConfiguration());

  17: _response = productController.Get(2);

  18: var responseResult =

  19: JsonConvert.DeserializeObject<Product>(_response.Content.ReadAsStringAsync().Result);

  20: Assert.AreEqual(_response.StatusCode,

  21: HttpStatusCode.OK);

  22: AssertObjects.PropertyValuesAreEquals(responseResult,

  23: _products.Find(a =>

  24: a.ProductName.Contains("Mobile")));

  25: }

I have used a sample product id “2” to test the method. Again we get the result in JSON format inside HttpResponse that we de-serialize. First assert compares for the status code and second assert makes use of AssertObject class to compare the properties of the returned product with the actual “mobile” named product having product id as 2 from the list of products.

image

 

image

Testing Exceptions from WebAPI

NUnit provides flexibility to even test the exceptions. Now if we want to unit test the alternate exit point for GetProductById() method i.e. an exception so what should we do? Remember it was easy to test the alternate exit point for business services method because it returned null. Now in case of exception, NUnit provides an attribute ExpectedException. We can define the type of exception expected to be returned from the method call. Like if I make a call to the same method with wrong id, the expectation is that it should return an exception with ErrorCode 1001 and an error description telling “No product found for this id.”.

So in our case the expected exception type is ApiDataException (got it from controller method).Therefore we can define the Exception attribute as [ExpectedException(“WebApi.ErrorHelper.ApiDataException”)]

And call the controller method with wrong id. But there is an alternate way to assert the exception. NUnit also provides us flexibility to assert the exception by Assert.Throws. This statement asserts the exception and returns that particular exception to the caller.Once we get that particular exception we can assert it with its ErrorCode and ErrorDescription or on whatever property you want to.

3. GetProductByWrongIdTest ()
   1:

   2: [Test]

   3: //[ExpectedException("WebApi.ErrorHelper.ApiDataException")]

   4: public void GetProductByWrongIdTest()

   5: {

   6: var productController = new

   7: ProductController(_productService)

   8: {

   9: Request = new HttpRequestMessage

  10: {

  11: Method = HttpMethod.Get,

  12: RequestUri = new Uri(ServiceBaseURL +

  13: "v1/Products/Product/productid/10")

  14: }

  15: };

  16: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  17: new HttpConfiguration());

  18: var ex = Assert.Throws<ApiDataException>(() =>

  19: productController.Get(10));

  20: Assert.That(ex.ErrorCode,Is.EqualTo(1001));

  21: Assert.That(ex.ErrorDescription, Is.EqualTo("No product 

  22: found for this id."));

  23: }

In the above code, I have commented out the Exception attribute approach and followed the alternate one.

I called the method with wrong id (that does not exists in our product list) in the statement,

   1:

   2: var ex = Assert.Throws<ApiDataException>(() =>

   3: productController.Get(10));

The above statement expects ApiDataException and stores the returned exception in “ex”.

Now we can assert the “ex” exception properties like ErrorCode and ErrorDescription with the actual desired result.

image

image

4. GetProductByInvalidIdTest ()

Another exit point for the same method is that if request for a product comes with an invalid it then an exception is thrown. Let’s test that method for this scenario,

   1:

   2: [Test]

   3: // 

   4: [ExpectedException("WebApi.ErrorHelper.ApiException")]

   5: public void GetProductByInvalidIdTest()

   6: {

   7: var productController = new

   8: ProductController(_productService)

   9: {

  10: Request = new HttpRequestMessage

  11: {

  12: Method = HttpMethod.Get,

  13: RequestUri = new Uri(ServiceBaseURL +

  14: "v1/Products/Product/productid/-1")

  15: }

  16: };

  17: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  18: new HttpConfiguration());

  19: var ex = Assert.Throws<ApiException>(() =>

  20: productController.Get(-1));

  21: Assert.That(ex.ErrorCode,

  22: Is.EqualTo((int)HttpStatusCode.BadRequest));

  23: Assert.That(ex.ErrorDescription, Is.EqualTo("Bad 

  24: Request..."));

  25: }

I passed an invalid id i.e. -1 to the controller method and it throws an exception of type ApiException with ErrorCode equal to HttpStatusCode.BadRequest and ErrorDescription equal to “bad Request…”.

image

Test result,

image

i.e. Passed. Other tests are very much of same kind like I explained.

5. CreateProductTest ()
   1:

   2: /// <summary>

   3: /// Create product test

   4: /// </summary>

   5: [Test]

   6: public void CreateProductTest()

   7: {

   8: var productController = new

   9: ProductController(_productService)

  10: {

  11: Request = new HttpRequestMessage

  12: {

  13: Method = HttpMethod.Post,

  14: RequestUri = new Uri(ServiceBaseURL +

  15: "v1/Products/Product/Create")

  16: }

  17: };

  18: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  19: new HttpConfiguration());

  20: var newProduct = new ProductEntity()

  21: {

  22: ProductName = "Android Phone"

  23: };

  24: var maxProductIDBeforeAdd = _products.Max(a =>

  25: a.ProductId);

  26: newProduct.ProductId = maxProductIDBeforeAdd + 1;

  27: productController.Post(newProduct);

  28: var addedproduct = new Product() { ProductName =

  29: newProduct.ProductName, ProductId = newProduct.ProductId };

  30: AssertObjects.PropertyValuesAreEquals(addedproduct,

  31: _products.Last());

  32: Assert.That(maxProductIDBeforeAdd + 1,

  33: Is.EqualTo(_products.Last().ProductId));

  34: }

6. UpdateProductTest ()
   1:

   2: /// <summary>

   3: /// Update product test

   4: /// </summary>

   5: [Test]

   6: public void UpdateProductTest()

   7: {

   8: var productController = new

   9: ProductController(_productService)

  10: {

  11: Request = new HttpRequestMessage

  12: {

  13: Method = HttpMethod.Put,

  14: RequestUri = new Uri(ServiceBaseURL +

  15: "v1/Products/Product/Modify")

  16: }

  17: };

  18: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  19: new HttpConfiguration());

  20: var firstProduct = _products.First();

  21: firstProduct.ProductName = "Laptop updated";

  22: var updatedProduct = new ProductEntity() { ProductName =

  23: firstProduct.ProductName, ProductId = firstProduct.ProductId };

  24: productController.Put(firstProduct.ProductId,

  25: updatedProduct);

  26: Assert.That(firstProduct.ProductId, Is.EqualTo(1)); // 

  27: hasn't changed

  28: }

7. DeleteProductTest ()
   1:

   2: /// <summary>

   3: /// Delete product test

   4: /// </summary>

   5: [Test]

   6: public void DeleteProductTest()

   7: {

   8: var productController = new

   9: ProductController(_productService)

  10: {

  11: Request = new HttpRequestMessage

  12: {

  13: Method = HttpMethod.Put,

  14: RequestUri = new Uri(ServiceBaseURL +

  15: "v1/Products/Product/Remove")

  16: }

  17: };

  18: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  19: new HttpConfiguration());

  20: int maxID = _products.Max(a => a.ProductId); // Before 

  21: removal

  22: var lastProduct = _products.Last();

  23: // Remove last Product

  24: productController.Delete(lastProduct.ProductId);

  25: Assert.That(maxID, Is.GreaterThan(_products.Max(a =>

  26: a.ProductId))); // Max id reduced by 1

  27: }

8. DeleteInvalidProductTest ()
   1:

   2: /// <summary>

   3: /// Delete product test with invalid id

   4: /// </summary>

   5: [Test]

   6: public void DeleteProductInvalidIdTest()

   7: {

   8: var productController = new

   9: ProductController(_productService)

  10: {

  11: Request = new HttpRequestMessage

  12: {

  13: Method = HttpMethod.Put,

  14: RequestUri = new Uri(ServiceBaseURL +

  15: "v1/Products/Product/remove")

  16: }

  17: };

  18: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  19: new HttpConfiguration());

  20: var ex = Assert.Throws<ApiException>(() =>

  21: productController.Delete(-1));

  22: Assert.That(ex.ErrorCode,

  23: Is.EqualTo((int)HttpStatusCode.BadRequest));

  24: Assert.That(ex.ErrorDescription, Is.EqualTo("Bad 

  25: Request..."));

  26: }

9. DeleteProductWithWrongIdTest ()
   1:

   2: /// <summary>

   3: /// Delete product test with wrong id

   4: /// </summary>

   5: [Test]

   6: public void DeleteProductWrongIdTest()

   7: {

   8: var productController = new

   9: ProductController(_productService)

  10: {

  11: Request = new HttpRequestMessage

  12: {

  13: Method = HttpMethod.Put,

  14: RequestUri = new Uri(ServiceBaseURL +

  15: "v1/Products/Product/remove")

  16: }

  17: };

  18: productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,

  19: new HttpConfiguration());

  20: int maxID = _products.Max(a => a.ProductId); // Before 

  21: removal

  22: var ex = Assert.Throws<ApiDataException>(() =>

  23: productController.Delete(maxID+1));

  24: Assert.That(ex.ErrorCode, Is.EqualTo(1002));

  25: Assert.That(ex.ErrorDescription, Is.EqualTo("Product is 

  26: already deleted or not exist in system."));

  27: }

All the above mentioned tests are self-explanatory and are more like how we tested BusinessServices.the idea was to explain how we write tests in WebAPI. Let’s run all the tests through NUnit UI.

Test through NUnit UI

image

1. Step 1: Launch NUnit UI. I have already explained how to install NUnit on the windows machine. Just launch the NUnit interface with its launch icon,

image

2. Step 2 : Once the interface opens, click on File -> New Project and name the project as WebAPI.nunit and save it at any windows location.

image

 

image

 

image

3. Step 3: Now, click on Project-> Add Assembly and browse for ApiController.Tests.dll (The library created for your unit test project when compiled)

image

image

4. Step 4: Once the assembly is browsed, you’ll see all the unit tests for that test project gets loaded in the UI and are visible on the interface.

image

5. At the right hand side panel of the interface, you’ll see a Run button that runs all the tests of Api controller. Just select the node ApiController in the tests tree on left side and press Run button on the right side.

image

Once you run the tests, you’ll get green progress bar on right side and tick mark on all the tests on left side. That means all the tests are passed. In case any test fails, you’ll get cross mark on the test and red progress bar on right side.

image

But here, all of our tests are passed.

image

Integration Tests

I’ll give just an idea of what integration tests are and how can we write it. Integration tests doesn’t run in memory. For WebAPI’s the best practice to write integration test is when the WebAPI is self hosted.You can try writing integration test when you host an API, so that you you get an actual URL or endpoint of the service you want to test.The test is performed on actual data and actual service. Let’s proceed with an example. I have hosted my web api and I want to test GetAllProducts() method of WebAPI.My hosted URL for the particular controller action is http://localhost:50875/v1/Products/Product/allproducts.

Now I know that I am not going to test my controller method through dll reference but I want to actually test its endpoint for which I need to pass an authentication token because that end point is secured and can not be authorized until I add a secure token to the Request header. Following is the integration test for GetAllProducts().

   1:

   2: [Test]

   3: public void GetAllProductsIntegrationTest()

   4: {

   5: #region To be written inside Setup method specifically

   6: for integration tests

   7: var client = new HttpClient { BaseAddress = new

   8: Uri(ServiceBaseURL) };

   9: client.DefaultRequestHeaders.Add("Authorization", "Basic 

  10: YWtoaWw6YWtoaWw=");

  11: MediaTypeFormatter jsonFormatter = new

  12: JsonMediaTypeFormatter();

  13: _response = client.PostAsync("login",

  14: null).Result;

  15: if (_response != null && _response.Headers !=

  16: null && _response.Headers.Contains("Token") &&

  17: _response.Headers.GetValues("Token") != null)

  18: {

  19: client.DefaultRequestHeaders.Clear();

  20: _token =

  21: ((string[])(_response.Headers.GetValues("Token")))[0];

  22: client.DefaultRequestHeaders.Add("Token", _token);

  23: }

  24: #endregion

  25: _response =

  26: client.GetAsync("v1/Products/Product/allproducts/").Result;

  27: var responseResult =

  28: JsonConvert.DeserializeObject<List<ProductEntity>>(_response.Content.ReadAsStringAsync().Result);

  29: Assert.AreEqual(_response.StatusCode,

  30: HttpStatusCode.OK);

  31: Assert.AreEqual(responseResult.Any(), true);

  32: }

  33: I have used same class to write this test, but you should

  34: always keep your unit tests segregated from integration tests, so use another

  35: test project to write integration tests for web api. First we have to request a

  36: token and add it to client request,

  37: var client = new HttpClient { BaseAddress = new

  38: Uri(ServiceBaseURL) };

  39: client.DefaultRequestHeaders.Add("Authorization", "Basic 

  40: YWtoaWw6YWtoaWw=");

  41: MediaTypeFormatter jsonFormatter = new

  42: JsonMediaTypeFormatter();

  43: _response = client.PostAsync("login",

  44: null).Result;

  45: if (_response != null && _response.Headers !=

  46: null && _response.Headers.Contains("Token") &&

  47: _response.Headers.GetValues("Token") != null)

  48: {

  49: client.DefaultRequestHeaders.Clear();

  50: _token =

  51: ((string[])(_response.Headers.GetValues("Token")))[0];

  52: client.DefaultRequestHeaders.Add("Token", _token);

  53: }

In above code I have initialized the client with running service’s base URL i.e. http://localhost:50875. After initialization I am setting a default request header to call my login endpoint of Authentication controller to fetch valid token.Once the user logs in with his credentials he get a valid token. To read in detail about security refer my article on security in web api. I have passed base 64 string of my credentials username :Akhil and password:Akhil for basic authentication.Once request gets authenticated, I get a valid token in _response.Headers that I fetch and assign to _token variable and add to client’s default header with this line of code,

_token = ((string[])(_response.Headers.GetValues(“Token”)))[0];

client.DefaultRequestHeaders.Add(“Token”, _token);

Then I am calling the actual service URL from the same client,

_response = client.GetAsync(“v1/Products/Product/allproducts/”).Result;

And we get the result as success. Follow the screen shots.

Step1: Get Token

image

We got the token : 4bffc06f-d8b1-4eda-b4e6-df9568dd53b1. Now since this is a real time test.This token should get saved in database. Let’s check.

Step2 : Check database

image

We got the same token in database.It proves we are testing on real live URL.

Step3 : Check ResponseResult

Here we got the response result with 6 products where first product id is 1 and product name is “Laptop”. Check the database for complete product list,

image

We get the same data. This proves our test is a success.

image

Likewise you can write more integration tests.

Difference between Unit tests and Integration tests

I’ll not write much, but wanted to share one of my good readings on this from this reference link

 

Unit Testing Integration Testing
Unit testing is a type of testing to check if the small piece of code is doing what it is supposed to do. Integration testing is a type of testing to check if different pieces of the modules are working together.
Unit testing checks a single component of an application. The behavior of integration modules is considered in the Integration testing.
The scope of Unit testing is narrow, it covers the Unit or small piece of code under test. Therefore while writing a unit test shorter codes are used that target just a single class. The scope of Integration testing is wide, it covers the whole application under test and it requires much more effort to put together.
Unit tests should have no dependencies on code outside the unit tested. Integration testing is dependent on other outside systems like databases, hardware allocated for them etc.
This is first type of testing is to be carried out in Software testing life cycle and generally executed by developer. This type of testing is carried out after Unit testing and before System testing and executed by the testing team.
Unit testing is not further sub divided into different types. Integration testing is further divided into different types as follows:
Top-down Integration, Bottom-Up Integration and so on.
Unit testing is starts with the module specification. Integration testing is starts with the interface specification.
The detailed visibility of the code is comes under Unit testing. The visibility of the integration structure is comes under Integration testing.
Unit testing mainly focus on the testing the functionality of individual units only and does not uncover the issues arises when different modules are interacting with each other. Integration testing is to be carried out to discover the the issues arise when different modules are interacting with each other to build overall system.
The goal of Unit testing is to test the each unit separately and ensure that each unit is working as expected. The goal of Integration testing is to test the combined modules together and ensure that every combined module is working as expected.
Unit testing comes under White box testing type. Integration testing is comes under both Black box and White box type of testing.

 

Reference : http://www.softwaretestingclass.com/what-is-difference-between-unit-testing-and-integration-testing/

Conclusion

image

In this article, we learnt how to write unit tests for Web API controller and primarily on basic CURD operations. The purpose was to get a basic idea on how unit tests are written and executed. You can add your own flavor to this that helps you in your real time project.We also learned about how to write integration tests for WebAPI endpoints. I hope this was useful to you. You can download the complete source code of this article with packages from GitHub. Happy coding J

Read more:

Other Series

My other series of articles:

For more technical articles you can reach out to CodeTeddy.

Advertisements

Author: Akhil Mittal

Akhil Mittal is a Microsoft MVP,C# Corner MVP, Code project MVP, blogger, programmer by heart and currently working as a Sr. Analyst in Magic Software and have an experience of more than 9 years in C#.Net. He holds a B.Tech in Computer Science and hold a diploma in Information Security and Application Development. His work experience includes Development of Enterprise Applications using C#,.Net and Sql Server,Analysis, Product Management as well as Research and Development. He is a MCP in Web Applications(MCTS-70-528,MCTS-70-515) and .Net Framework 2.0 (MCTS-70-536).