1
votes

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));
}
1
Please fix your code style and add more description of what you need. - Anton
This appears to be an XY problem. - Nkosi

1 Answers

0
votes

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.