nsubstitute/NSubstitute

How to get the StatusCode from a IActionResult?

saigkill opened this issue · 1 comments

Question
Please excuse my dumb question, i'm just starting with testing. I have a controller IActionResult method, what returns a OK or BadRequest. The Unitverse Extension helped me and generates that test:

`[TestInitialize]
public void SetUp()
{
this._cache = Substitute.For();
this._testClass = new ActiveUsersController(this._cache);
}

[TestMethod]
public void CanCallGet()
{
// Act
var result = this._testClass.Get();

// Assert
Assert.Fail("Create or modify test");
}`

So the mocked class was used with the Get method. The result method contains some information and the StatusCode too. So i tried result.StatusCode but it isnt accessable.

Maybe i missed anytthing?

I think you came to the wrong place. NSubstitute is a library to mock dependencies. So of course it is normally used in conjunction of test frameworks.

So let us assume you have code like this (dont ask why ;)):

  public class ActiveUsersController : Controller
  {
    private readonly IMemoryCache _cache;

    public ActiveUsersController(IMemoryCache cache)
    {
      _cache = cache;
    }

    public IActionResult Get()
    {
      if (_cache.TryGetValue(42, out var value))
      {
        return Ok(value);
      }

      return NotFound();
    }
  }

So your controller is taking special action, if your cache contains the key 42. You dont want to hassle with the actual implemention of the cache. That is what NSubstitute is all about. Create code covering this case.

While of course part of the test, the actual validation is a matter of other libraries.

So your test e.g. could be written like this:

  [TestClass]
  public class ActiveUsersControllerUnitTests
  {

    [TestMethod]
    public void CacheContains42_Get_ReturnsOk()
    {
      // Arrange
      var cache = Substitute.For<IMemoryCache>();
      cache.TryGetValue(42, out Arg.Any<object>()!)
        .Returns(c =>
        {
          c[1] = "value";
          return true;
        });
      var cut = new ActiveUsersController(cache);

      // Act
      var result = cut.Get();

      // Assert
      result.Should()
        .BeOfType<OkObjectResult>()
        .Which.Value.Should().Be("value");
    }
  }

IActionResult is an interface. When you return Ok, you get either an OkResult of an OkObjectResult. So you have to cast it to the result you are expecting. (I am using FluentAssertions for assertion)

Nothing wrong with your question,k everyone has to start at some point, but it has nothing to do with NSubstitute