'How do I assert against a Boolean value to confirm that causes an exception to be thrown in C#?
I'm writing my unit tests for my application and I'm trying to make sure that an exception is throw in one of my services. That exception is throw based on a true/false condition but I'm not sure how to get it to work. I am using NSubstitute for mocking in my unit tests and MSTest for the testing framework.
Here is my unit test.
private readonly FileRepository _sut;
private readonly BlobServiceClient _blobServiceClient = Substitute.For<BlobServiceClient>();
private readonly BlobContainerClient _blobContainerClient = Substitute.For<BlobContainerClient>();
private readonly BlobClient _blobClient = Substitute.For<BlobClient>();
public BlobStorageFileRepositoryTests()
{
_blobServiceClient.GetBlobContainerClient(default).ReturnsForAnyArgs(_blobContainerClient);
_blobContainerClient.GetBlobClient(default).ReturnsForAnyArgs(_blobClient);
_sut = new FileRepository(_blobServiceClient);
}
[TestMethod]
[ExpectedException(typeof(Exception), "file already")]
public async Task PlaceFileInStorage_ShouldReturnErrorIfFileExists()
{
// Arrange
var fileName = "myfile.pdf";
// Act
_sut.CheckFileExists(fileName).Returns(true);
}
As you can see the test method is decorated with the expected exception type and the message we expect to see. The error I get when I attempt to run this test is:
Test method threw exception NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException, but exception System.Exception was expected. Exception message: NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException: Can not return value of type Task`1 for Response`1.get_Value (expected type Boolean).
This makes sense as I am returning a boolean when I declare CheckFileExists but I want to know how I can access the thrown error that occurs when the boolean is false. Here is the service itself so you can see the construction of this method.
public async Task PlaceFileInStorage(string fileName, byte[] data)
{
//Check if the file exists first
var fileCheck = await CheckFileExists(fileName);
var file = fileName.Insert(0, DateTime.UtcNow.ToString("yyyy-MM-dd-HH:mm:ss"));
if (fileCheck.Equals(false))
{
try
{
var blob = _container.GetBlobClient(fileName);
await using var ms = new MemoryStream(data, false);
await blob.UploadAsync(ms, CancellationToken.None);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
throw new Exception("This file already exists");
}
You can see above that it checks if the files exists in storage first and then we either save or return an exception based on that. So, in my unit test how can I check that the exception is thrown when the fileCheck condition is true?
Many thanks
Solution 1:[1]
I am not sure how NSubstitue works, but you're clearly receiving an exception because the mock you're trying to do is incorrect, hence your test fails because is NSubstitute who throws the exception, not your FileRepository class.
Now, if you want to check whether a tested method returns an exception of the expected type, you can use the Assert class:
Assert.ThrowsExceptionAsync<Exception>(async () => await _sut.PlaceFileInStorage(filename, data));
This assert will succeed only if the exception throw is of the type you specify.
Here you have the reference for this method: https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.throwsexceptionasync?view=visualstudiosdk-2022#microsoft-visualstudio-testtools-unittesting-assert-throwsexceptionasync-1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DharmanBot |
