虽然抛出异常,但测试ExpectedException的单元测试失败

时间:2017-05-18 12:48:26

标签: c# unit-testing

开始使用MSTest

在C#中实现单元测试

在这个特定的测试中,我试图验证是否正在抛出ArgumentNullException。即使我的代码确实抛出了异常,我的测试也失败了,因为它显然没有收到那种类型的异常。

我哪里错了?一定要简单......

我的测试看起来像这样:

[TestMethod()]
[ExpectedException(typeof(ArgumentNullException), "A null HttpContent was inappropriately allowed")]
public void Test_HttpContent_Null_Throws_Exception()
{
    MultipartFormDataMemoryStreamProvider provider = new MultipartFormDataMemoryStreamProvider();
    Assert.ThrowsException<ArgumentNullException>(()=>provider.GetStream(null, null));
}

GetStreams()方法如下所示:

public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
    {
        if (parent == null)
            throw new ArgumentNullException("parent");

        if (headers == null)
            throw new ArgumentNullException("headers");

        var contentDisposition = headers.ContentDisposition;
        if (contentDisposition == null)
            throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part.");

        _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
        return base.GetStream(parent, headers);
    }

1 个答案:

答案 0 :(得分:4)

此行中的断言正在处理异常:

Assert.ThrowsException<ArgumentNullException>(()=>provider.GetStream(null, null));

因此,就ExpectedException而言,测试框架并没有被抛出。您可以删除该属性,也可以删除断言:

[TestMethod()]
[ExpectedException(typeof(ArgumentNullException), "A null HttpContent was inappropriately allowed")]
public void Test_HttpContent_Null_Throws_Exception()
{
    MultipartFormDataMemoryStreamProvider provider = new MultipartFormDataMemoryStreamProvider();
    provider.GetStream(null, null);
}