Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignoring thrown exceptions in an MSTest test

Suppose we wish to test the following method. It’s a contrived network call that logs a warning if the request failed and then throws after three attempts.

    private async Task<HttpResponseMessage> ContrivedNetworkRequest(ILogger<IContrived> logger, HttpClient client)
    {
        for (var i = 0; i < 3; i++)
        {
            var response = await client.GetAsync("http://example.com");
            if (response.IsSuccessStatusCode)
                return response;

            logger.LogWarning("Warning!");
        }

        throw new ContrivedException("Error!");
    }

We want to only test that a warning log was recorded. That is, we don’t want to test that the method throws. Throwing is tested elsewhere and we don’t want to have two asserts testing both logging and throwing in the same test for this scenario.

Is there a way to tell MSTest V3 (with .NET 8) to just exit the tested method when an exception is hit as we’re only interested in other functionality?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is there a way to tell MSTest V3 (with .NET 8) to just exit the tested method when an exception is hit

An exception already exits a method. The test can simply catch that exception like any other code. For example:

// arrange
var logger = CreateMockLogger();
var client = CreateMockClient();

// act
try
{
    ContrivedNetworkRequest(logger, client)
}
catch (ContrivedException) { }

// assert
// ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading