针对Catch部分功能的Nunit测试用例

use*_*098 0 c# nunit unit-testing ncover

public int ReturnFromDB(int input)
{
    try
    {
         return repositorymethod(input);
    }
    catch(RepositoryException ex)
    {
         Throw new ParticularException("some message",ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

repositorymethod()使用select查询从db返回整数数据.

对于积极的情况,我可以断言返回值.但是这个方法在NCover中的代码覆盖率仍然是60%.

如何测试此方法的Catch部分?如何触发异常部分?即使我给出一个负值作为输入,返回0也不会触发异常.

met*_*bed 5

这是嘲弄的好方案.如果您的存储库是一个带有接口的独立类,则可以使用将实际存储库换出来显式抛出异常的模拟.

// Interface instead of concrete class
IRepository repository;
...

// Some way to inject a mock repo.
public void SetRepository(IRepository repo)
{
    this.repository = repo;
}

public int ReturnFromDB(int input)
{
    try
    {
         return repository.method(input);
    }
    catch(RepositoryException ex)
    {
         throw new ParticularException("some message",ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

public class MockRepo : IRepository
{
    public int method(int input)
    {
        throw new RepositoryException();
    }
}
Run Code Online (Sandbox Code Playgroud)

有很多方法可以将这个模拟注入你的课程.如果您使用的是依赖注入容器(如Spring或MEF),则可以将它们配置为为测试注入模拟.上面显示的setter方法仅用于演示目的.