I'm following this guide and I'm trying to write a similar test with MS Test. Does MS Test have an IsType()
that returns the object when the cast is successful?
From this comparison, I see I can use IsInstanceOfType()
but the return type is void
.
I'm trying to implement this line in MS Test:
var badRequestResult = Assert.IsType<BadRequestObjectResult>(result);
[Fact]
public async Task IndexPost_ReturnsBadRequestResult_WhenModelStateIsInvalid()
{
// Arrange
var mockRepo = new Mock<IBrainstormSessionRepository>();
mockRepo.Setup(repo => repo.ListAsync()).Returns(Task.FromResult(GetTestSessions()));
var controller = new HomeController(mockRepo.Object);
controller.ModelState.AddModelError("SessionName", "Required");
var newSession = new HomeController.NewSessionModel();
// Act
var result = await controller.Index(newSession);
// Assert
var badRequestResult = Assert.IsType<BadRequestObjectResult>(result);
Assert.IsType<SerializableError>(badRequestResult.Value);
}
Yes, I could cast using as
and then use IsInstanceOfType
... just wondering if there is a one-liner.
var badRequestResult = result as BadRequestObjectResult;
Assert.IsInstanceOfType(badRequestResult, typeof(BadRequestObjectResult));
Reference: Add to MSTest Request
There is no equivalent version in MSTest that I have ever come across.
also if casting, then there is no need to check if instance is of type. Just check if it is not null.
// Act
var result = await controller.Index(newSession);
// Assert
var badRequestResult = result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult, "Expected BadRequestObjectResult");
Assert.IsInstanceOfType(badRequestResult.Value, typeof(SerializableError));
Otherwise, you can create your own assertion
public static class AssertExtension {
public static TExpected AssertIsType<TExpected>(this object actual, string message = null)
where TExpected : class {
TExpected result = actual as TExpected;
Assert.IsNotNull(result, message);
return result;
}
}
that provides the desired behavior
// Assert
var badRequestResult = result.AssertIsType<BadRequestObjectResult>();
badRequestResult.Value.AssertIsType<SerializableError>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With