MOQ – validationexception被抛出

我使用MOQ框架进行测试。 我有一个场景,我期望抛出一个错误exception。 我如何validation它被抛出?

public void Koko(List list) { foreach(string? str in list) { if (str != null) someProperty.Foo(str); else throw new FormatException(); } } 

提前致谢。

如果你想validation抛出exception(通过你自己的代码),那么Moq不是你选择的工具。 只需使用其中一个unit testing框架即可。

的xUnit / NUnit的:

 Assert.Throws(() => foo.Bar()); 

流利断言:

 Action act = () => foo.Bar(); act.ShouldThrow(); 

http://fluentassertions.codeplex.com/documentation

http://www.nunit.org/index.php?p=exceptionAsserts&r=2.6.2

我可能会误读你的意图,但据我所知,没有必要对mock进行任何操作以测试exception是否被抛出。

看起来你有一个带有方法Foo的类,它接受一个字符串 – 让我们调用这个InnerClass

 public class InnerClass { public virtual void Foo(string str) { // do something with the string } } 

和一个包含InnerClass作为属性的类(someProperty),它有一个成员Koko,它将List 作为参数

 public class OuterClass { private readonly InnerClass someProperty; public OuterClass(InnerClass someProperty) { this.someProperty = someProperty; } public void Koko(List list) { foreach (var str in list) { if (str != null) someProperty.Foo(str); else throw new FormatException(); } } } 

注意:我无法获得List 进行编译 – 告诉我底层类型(字符串)必须是不可为空的。 AFAIK,只需要使值类型可以为空,引用类型可以隐式为可空。

看起来你想测试一下,如果你传入一个字符串列表,其中任何一个字符串都是null,抛出FormatException。

如果是这样,那么MOQ的唯一原因就是让我们不要担心InnerClassfunction。 Foo是一种方法,因此,除非我们使用严格的模拟,否则我们可以创建一个没有其他设置的InnerClass模拟。

有一个属性[ExpectedException] ,我们可以用它来标记我们的测试以validation是否抛出了exception。

 [TestMethod] [ExpectedException(typeof(FormatException))] public void ExceptionThrown() { var list = new List() { "Abel", "Baker", null, "Charlie" }; var outer = new OuterClass(new Mock().Object); outer.Koko(list); } 

如果抛出FormatException,则此测试将通过,否则将失败。

您可以使用NUnit Asserts测试抛出exception:

 Assert.That(() => testObject.methodToTest(), Throws.TypeOf()); 

请阅读本Moq简介 。 以下是在调用DoSomething方法时设置InvalidOperationException方法:

 mock.Setup(foo => foo.DoSomething()).Throws(); 

然后只需validation方法是否被调用。 如果它被调用,则引发exception

 mock.Verify(foo => foo.DoSomething()); 

一个老问题,但没有源代码实际显示解决方案是什么,所以这就是我做的:

 var correctExceptionThrown = false; try { _myClass.DoSomething(x); } catch (Exception ex) { if (ex.Message == "Expected message") correctExceptionThrown = true; } Assert.IsTrue(correctExceptionThrown); 

注意而不是检查消息,您可以捕获特定类型的exception(通常更可取)。

好的,我以下面的方式解决了它。

由于exception打破了我的测试,我将方法调用放在try-catch中的Because块中。

然后我可以使用简单的validation。

感谢所有帮助者……

通过阅读这些答案,我意识到使用NUnit还有另一种方法可以做到这一点。 以下内容从exception中获取exception文本并validation错误消息文本。

 var ex = Assert.Throws(() => foo.Bar()); Assert.That(ex.Message, Is.EqualTo("Expected exception text"); 

我无法使用最新版本的NUnit来获取装饰/属性语法(AlanT的上述答案) – 不知道为什么,但无论我尝试做什么,它都会抱怨。