jeudi 28 janvier 2016

Trouble checking if the returnType is HttpNotFoundResult using xunit testing mvc.controller

I am trying to test a Microsoft.AspNet.Mvc.Controller that return Task<IActionResult> if the id passed in gets a hit, and returns a HttpNotFound() if no hits.

How can I, using xUnit, test to see if what i get back is the HttpNotFound or an actual result?

This is Controller method:

[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
    var company = await _repository.GetSingle(id);
    if (company == null)
        return HttpNotFound();

    return new ObjectResult(company);
}

And this is the test method (that is not working):

[Theory]
[InlineData("1")]
[InlineData("01")]
[InlineData("10")]
public async void TestGetSingleNonExistingCompany(string id)
{
    var controller = new CompanyController(new CompanyRepositoryMock());
    try
    {
        var res = await controller.Get(id);
        Assert.False(true);
    }
    catch (Exception e)
    {
        Assert.True(true);
    }
}

The problem I guess is that the controller.Get(id) does not actually throw an Exception, but I cannot use typeOf, because the type of the res variable is decided at compile-time, and not runtime.

When running the Assert.IsType :

[Theory]
[InlineData("1")]
[InlineData("01")]
[InlineData("10")]
public async void TestGetSingleNonExistingCompany(string id)
{
    var controller = new CompanyController(new CompanyRepositoryMock());
    var res = await controller.Get(id);
    Assert.IsType(typeof (HttpNotFoundResult), res.GetType());
}

I get this message:

Assert.IsType() Failure
Expected: Microsoft.AspNet.Mvc.HttpNotFoundResult
Actual:   System.RuntimeType

Can ideas?

Aucun commentaire:

Enregistrer un commentaire