Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing IActionResult content within vnext application

I have a vnext application in which I add this action :

[RoutePrefix("api/[controller]")]
public class AccountController : BaseController
{
    public IActionResult generatePasswd(int length)
    {
        throw new NotImplementedException();
    }
}

I added a simple unit test to test this action :

[Test]
public void GeneratePasswd_PasswdLength_NewPasswd()
{
    var mockNotifier = new Mock<INotifier>();
    var mockPaswordGenerator = new Mock<IPasswdGenerator>();

    AccountController AccMgr = new AccountController(mockNotifier.Object, mockPaswordGenerator.Object);

    int length = 0;

    IActionResult passwd = AccMgr.generatePasswd(length);

    Assert.IsTrue(passwd is HttpOkResult);     
}

I'd like to test the content if IActionResult response : for example test if its length not zero. How can I do this?

like image 781
Lamloumi Afif Avatar asked Dec 05 '25 05:12

Lamloumi Afif


1 Answers

You can verify that the returned interface is of a certain type and then cast it to said type, and assert on additional characteristics that you'd expect from it. Consider the following:

[Test]
public void GeneratePasswd_PasswdLength_NewPasswd()
{
    var mockNotifier = new Mock<INotifier>();
    var mockPaswordGenerator = new Mock<IPasswdGenerator>();

    var accMgr = new AccountController(mockNotifier.Object, mockPaswordGenerator.Object);

    IActionResult result = accMgr.generatePasswd(length);

    Assert.IsInstanceOfType(result , typeof(OkResult));    
}

Here was a similar SO Q & A. If you were returning an IActionResult that was a view, you could then take the model and perform assertions on it:

var vResult = result as ViewResult;
if(vResult != null)
{
    Assert.IsInstanceOfType(vResult.Model, typeof(YourModelType));
    var model = vResult.Model as YourModelType;
    if (model != null)
    {
        //...
    }
}

Update

In accordance with the official documentation, you can do something like this:

var result = Assert.IsType<HttpOkObjectResult>(controller.generatePasswd(length));
var password = Assert.IsType<string>(result.Value);

This would then assume that your implementation of the API would look something like this:

[Route("api/[controller]")]
public class AccountController : BaseController
{
    public IActionResult generatePasswd(int length)
    {
        // Where the generateImpl returns a string.
        return Ok(generateImpl(length));
    }
}
like image 187
David Pine Avatar answered Dec 07 '25 19:12

David Pine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!