-1

In the following function, I want to test the case where an exception is thrown using XUnit. The test should verify that the excpetion is correctly thrown.

public IDictionary<string, Label> Build(string content)
{
    try
    {
        var settings = new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Ignore
        };
        var contentStudioResponse = JsonConvert.DeserializeObject<ContentStudioResponse<CmsLabel>>(content, settings);

        if (contentStudioResponse?.Items == null)
        {
            _logger.Warning("No records found in content studio response for label:({@content})", content);
            return new Dictionary<string, Label>();

        }

        return contentStudioResponse.Items.ToDictionary(x => x.Key,
            x => new Label
            {
                Value = x.DynamicProperties.MicroContentValue
            }
        );
    }
    catch (Exception e)
    {
        _logger.Error(e, "Failed to deserialize or build contentstudio response for label");
        return new Dictionary<string, Label>();
    }
}

Below is my solution which is not working:

[Fact]
public void Builder_ThrowsException()
{
    string json_responsive_labels = "abcd";
    var builder = new LabelBuilder(_testLogger).Build(json_responsive_labels);
    Assert.Throws<Exception>(() => builder);
    //var sut = new LabelBuilder(_testLogger);            
    //Should.Throw<Exception>(() => sut.Build(json_responsive_labels));
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Please fix your code style and add more description of what you need. – Anton Mar 02 '20 at 13:10
  • This appears to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Nkosi Mar 02 '20 at 13:43

1 Answers1

0

Have a read through of this. This explains step by step on how to test for an exception being thrown.

However, based on what you have written, the code won't throw an exception since at this point you're only logging your exception and then returning a Dictionary.

   catch (Exception e)
   {
      _logger.Error(e, "Failed to deserialize or build contentstudio response for label");
      return new Dictionary<string, Label>();
   }

What you actually want to do is explicitly throw an exception like so:

   catch (Exception e)
   {
      throw new Exception();
   }

In doing so, your code will throw an exception which you can catch and test against.

Monza972
  • 51
  • 6
  • Thanks for your answer. but please let me know what should be the xUnit test case for my catch block. Yes is will not throw an exception. It will log error and create new object. how to the Unit test? – Asit Kumar Mohanty Mar 03 '20 at 06:59
  • That's down to what you are testing within that catch block. At the moment, the test would be incorrect given that you're explicitly looking for an exception to throw. Since you are logging in the `catch` block, you'd pass in a Mock logger to your `sut` and verify that the `Error()` method was called within your unit test. – Monza972 Mar 03 '20 at 11:46
  • //Now i have written my test case like the below. But if i make it Time.once then it is failing. Kindly suggest. – Asit Kumar Mohanty Mar 03 '20 at 12:12