C# NSSubstitute在创建替换时给出异常

C# NSSubstitute在创建替换时给出异常,c#,.net,nsubstitute,glass-mapper,C#,.net,Nsubstitute,Glass Mapper,我们正在尝试将Nunit测试集成到我们的web应用程序中。这里我们使用Nsubstitute作为模拟框架。 项目架构如下所示: Public class BaseService : Glass.Mapper.Sc.SitecoreContext { public BaseService(){} } Public class DerivedService : BaseService { IGenericRepository<Item> _genericReposito

我们正在尝试将Nunit测试集成到我们的web应用程序中。这里我们使用Nsubstitute作为模拟框架。 项目架构如下所示:

Public class BaseService : Glass.Mapper.Sc.SitecoreContext
{
    public BaseService(){}
}

Public class DerivedService : BaseService
{
    IGenericRepository<Item> _genericRepository;

    public DerivedService ( IGenericRepository<Item> _repository)
    {
        _genericRepository= _repository;
    }

    public string DoSomethig(){}
}
公共类基本服务:Glass.Mapper.Sc.SitecoreContext
{
公共BaseService(){}
}
公共类派生服务:BaseService
{
IGenericRepository(通用repository);;
公共衍生服务(IGenericRepository\u存储库)
{
_genericRepository=\u存储库;
}
公共字符串DoSomethig(){}
}
现在,为了测试我的DerivedService类的DoSomething()方法,我正在创建我的存储库的替换项并伪造它的响应。这样我就可以测试我的服务代码了

[Test]
public void TestDoSomethigMethod()
{
    var repository = Substitute.For<IGenericRepository<Item>>();

    DerivedService tempService = new DerivedService(repository);
    // Throws an exception of type System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary. at base service constructor.
    var response = tempService.DoSomething();
}
[测试]
public void TestDoSomethigMethod()
{
var repository=Substitute.For();
DerivedService tempService=新的DerivedService(存储库);
//引发System.Collections.Generic.KeyNotFoundException类型的异常:字典中不存在给定的键。位于基本服务构造函数。
var response=tempService.DoSomething();
}
当我试图调用派生服务的实例时,它在baseService构造函数中抛出异常,表示(给定的键不在字典中) 我们使用windsor castle进行依赖注入&基类继承自Glass Mapper sitecore上下文类。 请让我知道,如果有人面临任何这样的问题或有一个解决办法


编辑:按照Pavel&Marcio的建议更新测试用例的代码。

您不应创建
衍生服务
的替代品,而应创建
IGenericRepository
的替代品,并将其注入
衍生服务

您将只为要模拟的零件创建替代品,而不是要测试的零件

以下是您应该做的:

[Test]
public void TestDoSomethigMethod()
{
    var repository = Substitute.For<IGenericRepository<Item>>();
    // Here you set up repository expectations
    DerivedService tempService = new DerivedService(repository);

    var response = tempService.DoSomething();

    // Here you assert the response
}
[测试]
public void TestDoSomethigMethod()
{
var repository=Substitute.For();
//您可以在这里设置存储库期望值
DerivedService tempService=新的DerivedService(存储库);
var response=tempService.DoSomething();
//在这里,您断言响应
}

NSubstitute
将仅代理
public
virtual
方法/属性。您应该替换接口或确保替换的类公开
公共虚拟方法。据我所知,您的不是
虚拟的
,虽然
NSubstitute
可以创建对象,但它不能有效地代理/模拟对象上的任何内容

此外,如果您的构造函数不是无参数的,请确保在替换时为每个参数提供替换(或真实实例)


这里有更多详细信息:

我也尝试过,但是在创建派生服务实例时,我得到了相同的异常。DerivedService tempService=新的DerivedService(存储库);DerivedService和BaseService的构造函数是否与示例中提供的完全相同?