首页 > 解决方案 > 如何在 Xunit 的 Catch 块中编写单元测试?

问题描述

在下面的函数中,我想测试使用 XUnit 抛出异常的情况。测试应验证是否正确抛出了异常。

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>();
    }
}

以下是我的解决方案,它不起作用:

[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));
}

标签: c#unit-testingexceptionxunit.netcatch-block

解决方案


通读一遍。这一步一步地解释了如何测试抛出的异常。

但是,根据您编写的内容,代码不会引发异常,因为此时您只是记录异常,然后返回一个Dictionary.

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

您真正想要做的是显式抛出一个异常,如下所示:

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

这样做时,您的代码将抛出一个异常,您可以捕获并对其进行测试。


推荐阅读