moq unit testing in c# web api

unit test web api controller request
moq c#
nunit testing c# web api
unit testing web api controllers using xunit
xunit testing web api controllers using moq
c# mock database for unit testing
.net core unit testing using xunit and moq
unit testing net core web api controllers using moq

I am tring to test one web api method in asp.net core 2.

Web api

method:

public IActionResult Delete(int id)
{
    try
    {
        var success = sportsService.DeleteSport(id);

        if (!success)
        {
            return new NotFoundResult();
        }
        return new OkResult();
    }
    catch (Exception e)
    {
        return new StatusCodeResult(400);
    }
}

Unit testing part:

private Mock<ISportsService> mockService;

[SetUp]
public void Setup()
{
    mockService.SetupSequence(x => x.DeleteSport(It.IsAny<int>())).
        Returns(true). // OkResult();
        Returns(false). // NotFoundResult()
        Throws(new Exception()); //Exception
}

Test method looks like this. What I am not clear about with this method is, what the right approach to testing the method is?

[Test]
public void TestStrategyControllerWithDelete()
{
    var result = controller.Delete(STRAT_ID);
    var okResult = result as ObjectResult;
    Assert.AreEqual(HttpStatusCode.NotFound, okResult.StatusCode);
    Assert.AreEqual(HttpStatusCode.OK, okResult.StatusCode);
    Assert.AreEqual(400, okResult.StatusCode);
}

and i am okresult as null ! and not able to get okResult.StatusCode

moq unit testing in c# web api, In this case, we can create a mock object and use it for the unit test. A mock object is an object that can act as a real object but can be controlled in test code. Moq is a library that allows us to create mock objects in test code. It is also available in NuGet. In this article, we will learn how to write unit test case for Web API controller. Following is a very common pattern in Unit Testing. In the first step, we will have to create test data for testing, using a mock or stub object. This approach will minimize the number of dependencies. Set up Unit test project

You can do something like this,

1) Success:

[Test]
public void Delete_ReturnsOkResult_IfDeleteSuccess()
{
  bool isSucceed = true;
  const int deleteId = 1234;

  this.MockSportService(isSucceed);

  var result = controller.Delete(deleteId);

  var okResult = result as ObjectResult;    
  Assert.AreEqual(HttpStatusCode.OK, okResult.StatusCode);
}

2) Failure:

[Test]
public void Delete_ReturnsNotFound_IfIdNotFound()
{
  bool isSucceed = false;
  const int deleteId = 1234;

  this.MockSportService(isSucceed);

  var result = controller.Delete(deleteId);

// Do proper asserts
}

3) Exceptions,

[Test]
public void Delete_ThrowsException_IfIdNotFound()
{
  bool isSucceed = false;
  const int deleteId = 1234;

   mockService.Setup(x => x.DeleteSport(It.IsAny<int>())).
        Throws(new Exception());

  // Act
  var result = controller.Delete(deleteId);

  // Assert
  Assert.True(result is StatusCodeResult); // Asserting that the return type is StatusCodeResult

  // Casting the result as StatusCodeResult object
  var statusCodeResult = result as StatusCodeResult;

  // Asserting the status code
  Assert.AreEqual(400, statusCodeResult.StatusCode);
}

And have the common method for mocking for success and failure,

private void MockSportService(bool isSucceed)
{
mockService.Setup(x => x.DeleteSport(deleteId)).Returns(isSucceed);
}

Moq - Unit Test In .NET Core App Using Mock Object, It's about testing only one thing, in isolation, by mocking how your dependencies a webapi project, this should contain our production code and carry out the� I am working on this WebAPI project and I need to create unit tests for it. The base of the project was created using VS 2010 , and then an WebApi Module was added. The workings of the controller are kinda getting in the way of testing/mocking. I am using xUnit and Moq , but there is absolutely no need to stick with those two.

You'll need to call controler.Delete(...) method 3 times to have the moq return the different status/exception.

I would suggest having discreet tests for each returned status - one for each status (true/false) and one for the exception.

How YOU can Learn Mock testing in .NET Core and C# with Moq, Mocking framework come to a rescue here. You can mock the web service call. I will write unit tests for Web API Controller methods. I will be� The Unit test is code where we test all the code paths of the methods and ensure that the results are as expected. Mock object is the object that can act as a real object but can be controlled in test code. It is very useful in generating the objects which are used in test method. You can view or download source code from here.

C# Unit Testing with Moq, We can create a mock object and use it for the unit test. operations with xunit and moq, Assume your developing REST web API in .net core� 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. About Moq; Moq (pronounced “Mock-you” or just “Mock”) is the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and

Get started .net core application unit testing with xUnit and moq, Just got into using Moq rather than copying and modifying (apis- nearly all the same) this Duration: 38:52 Posted: Nov 15, 2018 Moq is a popular.NET library that helps mocking objects for testing. In essence it uses reflection and expressions to dynamically generate the mocks at runtime during your tests, based on specifications you declare using a fluent API. Now, there is a slight issue here, too.

Unit Testing: MOQ Framework, Net Core Web API application. And I will be using XUnit for the unit testing framework and Moq Duration: 25:21 Posted: Feb 4, 2018 GitHub - akhilmittal/UnitTesting-WebAPI-using-nUnit-and-Moq-framework.: The source code is a sample CURD operations application that describes implementation of Unit Testing in Web API using nUnit and Moq framework.

Comments
  • alright, so what should i write in [SetUp] public void Setup()? if we're already doing mockService.Setup(x => x.DeleteSport(deleteId)).Returns(true); inside!!, [setup] and [Test]
  • if anyone can explain all three cases ( ok, not found, exception) with example then it will be great. thanks
  • @Var the 3 cases will be very similar to the single one that is shown. You'll need to change the mockService.Setup() step and the assertion as those are what changes between each test.
  • can you please explain " asserts" for Exception? - Assert.IsInstanceOf(typeof(StatusCodeResult), result);? is correct? - i would love to check 400 status return or not
  • For returning the 400/BadRequest I think the following should work: Assert.AreEqual(400, (result as StatusCodeResult).StatusCode);. Alternatively you could return BadRequestResult and test for IsInstanceOf<BadRequestResult> to keep it consistent with the other return types.
  • Thanks, how about the bold text in my question any clue?
  • can you please explain " asserts" for Exception?
  • @Var - Edited the asserts for an exception. I hope this helps.
  • See @Fermin answer above - he nailed it