[英]Unit test that tests ExpectedException is failing though exception is thrown
Starting to implement unit tests in C#, using MSTest 开始使用MSTest在C#中实现单元测试
In this particular test I am trying to verify that an ArgumentNullException
is being thrown. 在这个特定的测试中,我试图验证是否抛出了
ArgumentNullException
。 Even though my code does throw the exception my test is failing because it apparently did not receive that type of exception. 即使我的代码确实抛出了异常,我的测试也失败了,因为它显然没有收到那种类型的异常。
Where am I going wrong? 我哪里错了? Bound 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 GetStreams()
method looks like this: 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);
}
The assert in this line is handling the exception: 这一行中的断言是处理异常:
Assert.ThrowsException<ArgumentNullException>(()=>provider.GetStream(null, null));
So the testing framework isn't seeing it being thrown as far as ExpectedException
is concerned. 因此,就
ExpectedException
而言,测试框架并没有看到它被抛出。 You can either remove the attribute, or the 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.