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

时间:2014-06-04 07:53:14

标签: c# unit-testing nunit ncover

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

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

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

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

1 个答案:

答案 0 :(得分: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);
    }
}

然后:

public class MockRepo : IRepository
{
    public int method(int input)
    {
        throw new RepositoryException();
    }
}

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

相关问题