Abaiz
Abaiz

Reputation: 63

Learning Unit testing using NUNIT for a sample micro service and getting an error

I just started learning unit testing using Nunit with my WebApi project.

I've developed one test case for my controller:

using Microsoft.AspNetCore.Mvc;

namespace HelloService.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelloController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("hello");
    }
}
}

This test

using NUnit.Framework;
using HelloService.Controllers;
using NUnit.Framework.Legacy;
using Microsoft.AspNetCore.Mvc;


namespace HelloService.Tests
{
public class HelloControllerTests
{
   [Test]
public async Task Should_Return_Hello()
{
// Arrange
var controller = new HelloController();

// Act
var actionResult = controller.Get() as 
OkObjectResult;

// Assert
Assert.IsNotNull(actionResult);
Assert.AreEqual("hello", actionResult.Value);
}
}
}

I am getting these errors "Assert does not contain a definition for IsNotNull" and "Assert does not contain a definition for AreEqual" Can any one please help me with this. Edited : I changed the Assert to Classical assert but When I do dotnet run I encounter error CS0579: Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute This error. I have add false this line in my .csproj file

Upvotes: 0

Views: 95

Answers (1)

Charlie
Charlie

Reputation: 13736

Although you don't say what version of NUnit you are using,(*) I'm guessing that it is version 4. Assert.AreEqual and Assert.NotNull are what NUnit calls "Classic Asserts". They are the very first form of NUnit assertions and were the only form until 2007, when the "Constraint-based Assert Model" was introduced. If you are using some documentation, which only mentions the classic model, then those docs are very old indeed.

If, for some reason, you want to use the legacy "Classic" assertions, you should replace "Assert" with "ClassicAssert" in your code each time you use one. Alternatively, you could install an older version of NUnit, prior to version 4, but that seems silly if you are just learning NUnit. My advice would be to start learning the newer model in the first place.

In that case, you would be writing

Assert.That(actionResult, Is.Not.Null);
Assert.That(actionResult.Value, Is.EqualTo("hello"));

You can let Intellisense or a more up to date version of the documentation guide you to other assertions.

Upvotes: 2

Related Questions