Unit test that checks for ExpectedException to fail, although an exception is thrown

Starting to implement unit tests in C # using MSTest

In this particular test, I am trying to check what is being thrown ArgumentNullException

. Even though my code is throwing an exception, my test fails as it apparently did not receive this type of exception.

Where am I going wrong? Tied to be something simple ....

My test looks like this:

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

      

And the method GetStreams()

looks like this:

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

      

+3


source to share


1 answer


The assertion on this line handles the exception:

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

      



Thus, the testing framework does not see that it has been selected before ExpectedException

. You can either remove the attribute or assert:

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

      

+4


source







All Articles