最小起订量 - 验证抛出异常 [英] MOQ - verify exception was thrown
问题描述
我和我的测试框架MOQ工作。
我有,我希望抛出一个故障异常的情况。 ?I
如何可以验证它被抛出
I working with MOQ framework for my testing. I have a scenario in which I expect a fault exception to be thrown. How can I verify it was thrown?
public void Koko(List<string?> list)
{
foreach(string? str in list)
{
if (str != null) someProperty.Foo(str);
else throw new FormatException();
}
}
在此先感谢。
推荐答案
我可能是错读你的意图,但据我可以看到有没有必要做任何的模拟,以测试该。异常被抛出
I may be mis-reading your intent, but as far as I can see there is no need to do anything to a mock in order to test that the exception has been thrown.
看起来你有这需要一个字符串的方法foo的类 - 让我们称之为这将InnerClass
It looks like you have a class with a method Foo that takes a string - lets call this InnerClass
public class InnerClass {
public virtual void Foo(string str) {
// do something with the string
}
}
和其中包含一个将InnerClass作为属性(someProperty),其中有一个成员江潮一类一个List<串GT;作为
and a class which contains an InnerClass as a property (someProperty) which has a member Koko that takes a List<string> as a parameter
public class OuterClass {
private readonly InnerClass someProperty;
public OuterClass(InnerClass someProperty) {
this.someProperty = someProperty;
}
public void Koko(List<string> list) {
foreach (var str in list) {
if (str != null)
someProperty.Foo(str);
else
throw new FormatException();
}
}
}
注意:我无法得到列表<串GT?;编译 - 告诉我,基本类型(字符串)必须是非空的。据我所知,人们只需要做出的价值类型为空,引用类型是隐式空。
NOTE: I cannot get List<string?> to compile - tells me that the underlying type (string) must be non-nullable. AFAIK, one only needs to make value types nullable, reference types are implicitly nullable.
看起来你想测试,如果你在哪里字符串任何人都空了出现FormatException被抛出的名单通过。
It looks like you want to test that if you pass in a list of strings where any of them are null that a FormatException is thrown.
如果是这样,那么对起订量的唯一理由是可以不用担心的功能将InnerClass释放我们。富是一个方法,因此,除非我们使用的是严格的嘲弄,我们就可以创建一个将InnerClass模拟,没有其他的设置。
If so, then the only reason for a MOQ is to release us from worrying about the InnerClass functionality. Foo is a method, so, unless we are using strict mocks, we can just create an InnerClass mock with no other setup.
有一个属性的[ExpectedException] ,使我们可以标记我们的测试,以验证例外是抛出。
There is an attribute [ExpectedException] with which we can tag our test to verify that the exception has been thrown.
[TestMethod]
[ExpectedException(typeof(FormatException))]
public void ExceptionThrown() {
var list = new List<string>() {
"Abel",
"Baker",
null,
"Charlie"
};
var outer = new OuterClass(new Mock<InnerClass>().Object);
outer.Koko(list);
}
此测试将通过,如果出现FormatException被抛出和失败,如果事实并非如此。
This test will pass if a FormatException is thrown and fail if it is not.
这篇关于最小起订量 - 验证抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!