How to simulate throwing an exception in Unit tests?

后端 未结 2 1328
盖世英雄少女心
盖世英雄少女心 2021-02-20 05:07

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

I want to be able to have 100% coverage of my code, but I can\'t test the code with exceptions that may oc

2条回答
  •  一整个雨季
    2021-02-20 06:09

    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.

提交回复
热议问题