如何模拟在单元测试中抛出异常? [英] How to simulate throwing an exception in Unit tests?

查看:3424
本文介绍了如何模拟在单元测试中抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以模拟一个例外,在C#中的单元测试被抛出?

How can I simulate an exception being thrown in C# unit tests?

我希望能有我的代码覆盖率达100%,但我不能可能发生的异常测试代码。例如我不能模拟可能出现的电力faluire

I want to be able to have 100% coverage of my code, but I can't test the code with exceptions that may occur. For example I cannot simulate a power faluire that may occur.

例如:

public void MyMethod()
{  
  try
  {  
  ...  
  }  
  catch(OutOfMemoryException e)
  {
  ...
  }  
  catch(RandomErrorFromDatabaseLayer e)
  {
  ...
  }  
}

我希望能够模拟任何一种例外的是在这个方法中,应该被抓住。结果
?是否有可能帮助我在这件事上的所有库

I want to be able to simulate any kind of exception that is in this method and should be caught.
Are there any libraries that may help me in this matter?

编辑1:
在完成我问有起订量任何帮助。

Edit 1: Any help in accomplishing what I asked with Moq?

推荐答案

您需要创建为可以抛出这些异常的真实对象矗立在一个模拟对象。然后,您可以创建测试,仅仅是这样的:

You need to create a mock object that stands in for the real objects that can throw these exceptions. Then you can create tests that simply are something like this:

public void ExampleMethod()
{
    throw new OutOfMemoryException();
}

如果您正在使用依赖注入框架它与取代真正的代码模拟代码变得更加容易。

If you are using a dependency injection framework it makes replacing the real code with the mock code much easier.

这篇关于如何模拟在单元测试中抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆