1

Can I catch the exception that appears in the log but not in the test?

I performed the test and it returned the status: OK, but in the log I have: Unexpected error publishing create package to Kafka. id = 5ec3eb81aa662c8a7c76e5e8. Exception: System.NullReferenceException: Object reference not set to an instance of an object.

How can I catch this exception in the test? I tried to use Try and catch (Exception) but nothing catches.

 [Fact]
    [DisplayTestMethodName]
    public async Task ExceptionTest()
    {
        try
        {
            var testRequest= @"{""Test1"":"1234"};
            var testRequestResp =
                await fixture.PostAsync(testRequest);
            Assert.Equal("HttpStatusCode: " + System.Net.HttpStatusCode.OK, "HttpStatusCode: " + testRequestResp.StatusCode);
        }
        catch (Exception ex)
        {
            Assert.True(ex == null, "Exception: " + ex.Message);
        }

Log VS log

Beret
  • 11
  • 3

2 Answers2

0

This means you are handling the NullReferenceException already somewhere in your PostAsync method and still returning status 200. That is a design decision to swallow the error and return "OK" (hopefully you are logging it or something at least).

A different approach would be to return a 500 status instead of 200, to indicate that an internal server error has occurred - then try and address the NullReferenceException.

You may also choose not to swallow the error in you PostAsync method and let it bubble all the way up. In that case, you could use:

var exception = await Assert.ThrowsAsync<NullReferenceException>(() => fixture.PostAsync(testRequest));

(Where testRequest was something you knew would trigger that error)

If getting a NullReferenceException is expected behavior and the request is still "OK" status, then somehow catching it in your test would make no sense.

crgolden
  • 4,332
  • 1
  • 22
  • 40
-1

I want to check that the exception "NullReferenceException" does not occur. I used your advice:

var exception = await Assert.ThrowsAsync<NullReferenceException>(() => fixture.PostAsync(testRequest));

But I don't catch this exception

enter image description here Where is the problem?

Beret
  • 11
  • 3
  • Yes. Like I said in my answer, that's because the exception is being swallowed inside the `PostAsync` method somewhere (probably in a `try`/`catch` block that doesn't rethrow it). – crgolden May 19 '20 at 20:56
  • this should be a comment on the other answer (you can edit a followup in at the end of your question) – Ruben Bartelink May 20 '20 at 07:22