【问题标题】:nsubstitute giving exception while creating substitutensubstitute 在创建替换时给出异常
【发布时间】:2015-10-21 15:00:31
【问题描述】:

我们正在尝试将 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 构造函数中抛出异常(字典中不存在给定的键) 我们使用温莎城堡进行依赖注入,基类继承自 Glass Mapper 站点核心上下文类。 如果有人遇到任何此类问题或对此有解决方案,请告诉我。

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

【问题讨论】:

    标签: c# .net nsubstitute glass-mapper


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您不应该创建DerivedService 的替代品,而应该创建IGenericRepository&lt;Item&gt; 的替代品并将其注入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
      }
      

      【讨论】:

      • 我也试过这个,但是在创建派生服务实例时我得到了同样的异常。 DerivedService tempService = new DerivedService(repository);
      • DerivedService 和 BaseService 的构造函数是否与您提供的示例完全相同?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多