我可以使用NUnit测试用例测试模拟存储库和真实存储库吗

我可以使用NUnit测试用例测试模拟存储库和真实存储库吗,nunit,Nunit,我希望能够在我的假存储库(使用列表)上运行测试 以及我的真实存储库(使用数据库),以确保我的模拟版本和实际生产存储库都能按预期工作。我认为最简单的方法是使用TestCase private readonly StandardKernel _kernel = new StandardKernel(); private readonly IPersonRepository fakePersonRepository; private readonly IPersonReposi

我希望能够在我的假存储库(使用列表)上运行测试 以及我的真实存储库(使用数据库),以确保我的模拟版本和实际生产存储库都能按预期工作。我认为最简单的方法是使用TestCase

    private readonly StandardKernel _kernel = new StandardKernel();
    private readonly IPersonRepository fakePersonRepository;
    private readonly IPersonRepository realPersonRepository;
    [Inject]
    public PersonRepositoryTests()
    {

        realPersonRepository = _kernel.Get<IPersonRepository>();
        _kernel = new StandardKernel(new TestModule());
        fakePersonRepository = _kernel.Get<IPersonRepository>();
    }



    [TestCase(fakePersonRepository)]
    [TestCase(realPersonRepository)]
    public void CheckRepositoryIsEmptyOnStart(IPersonRepository personRepository)
    {
        if (personRepository == null)
        {
            throw new NullReferenceException("Person Repostory never Injected : is Null");
        }
        var records = personRepository.GetAllPeople();

        Assert.AreEqual(0, records.Count());
    }
私有只读标准内核_kernel=新标准内核();
私有只读IPersonRepository fakePersonRepository;
私有只读IPersonRepository realPersonRepository;
[注入]
公共人员安置测试()
{
realPersonRepository=_kernel.Get();
_内核=新的标准内核(新的TestModule());
fakePersonRepository=_kernel.Get();
}
[测试用例(fakePersonRepository)]
[测试用例(realPersonRepository)]
public void CheckRepositoryIsEmptyOnStart(IPersonRepository personRepository)
{
if(personRepository==null)
{
抛出新的NullReferenceException(“从未注入的人:为Null”);
}
var records=personRepository.GetAllPeople();
Assert.AreEqual(0,records.Count());
}

但它需要一个恒定的表达式

您可能会查看该属性,尽管该属性可能会失败并出现相同的错误。否则,您可能必须满足于两个单独的测试,这两个测试都调用第三个方法来处理所有公共测试逻辑。

属性是属性的编译时修饰,因此您在TestCase属性中放入的任何内容都必须是编译器可以解析的常量

您可以尝试以下方法(未经测试):

然而,这有点难看,因为我认为您的两个不同的实现可能具有不同的构造函数参数。另外,您真的不希望所有的动态类型实例化代码都干扰测试

一个可能的解决方案可能是这样的:

[TestCase("FakePersonRepository")]
[TestCase("TestPersonRepository")]
public void CheckRepositoryIsEmptyOnStart(string repoType)
{
    // Write a helper class that accepts a string and returns a properly 
    // instantiated repo instance. 
    var repo = PersonRepoTestFactory.Create(repoType);

    // your test here
}
底线是,测试用例属性必须采用常量表达式。但是,您可以通过将实例化代码推入工厂来实现所需的结果

[TestCase("FakePersonRepository")]
[TestCase("TestPersonRepository")]
public void CheckRepositoryIsEmptyOnStart(string repoType)
{
    // Write a helper class that accepts a string and returns a properly 
    // instantiated repo instance. 
    var repo = PersonRepoTestFactory.Create(repoType);

    // your test here
}