nsubstitute在创建替换时给出异常

时间:2015-10-20 09:56:48

标签: c# .net nsubstitute glass-mapper

我们正在尝试将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(){}
}

现在要测试我的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();
}

当我尝试调用派生服务的实例时,它会在baseService构造函数中抛出异常(在字典中没有给定的键) 我们正在使用windsor城堡进行依赖注入&amp; Base Class继承自Glass Mapper sitecore上下文类。 如果有人遇到任何此类问题或有解决方案,请告诉我。

编辑:根据Pavel&amp; amp;马尔西奥。

2 个答案:

答案 0 :(得分:0)

您不应该为DerivedService创建替代,而是为IGenericRepository<Item>创建替代,并将其注入DerivedService

您只会为要模拟的部分创建替代品,而不是您要测试的部分。

这是你应该做的:

[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
}

答案 1 :(得分:0)

NSubstitute代理 publicvirtual方法/属性。您应该替换接口或确保替换的类公开public virtual方法。据我所知,你的virtual不是NSubstitute<!--begin.rcode results="asis", echo=FALSE, warning=FALSE, message=FALSE library(RJSONIO) library(MASS) set.seed(1234) data <- data.frame("Sample"=rbeta(1000,10,15)) out <- paste("<script type='text/javascript'> var json ='", jsonlite::serializeJSON(data), "';</script>", sep="") end.rcode--> 可以创建对象,它无法在其上有效地代理/模拟任何内容。

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

此处有更多详情:http://nsubstitute.github.io/help/creating-a-substitute/