模拟{get; }(Moq) [英] Mocking an interface which is { get; } only (Moq)

查看:92
本文介绍了模拟{get; }(Moq)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IUnitOfWork接口,其中包含到我们所有存储库的映射,如下所示:

I have an IUnitOfWork interface which contains mappings to all of our repositories, like so:

public interface IUnitOfWork : IDisposable
{
    IRepository<Client> ClientsRepo { get; }
    IRepository<ConfigValue> ConfigValuesRepo { get; }
    IRepository<TestRun> TestRunsRepo { get; }
    //Etc...
}

我们的IRepository类如下:

public interface IRepository<T>
{
    T getByID(int id);
    void Add(T Item);
    void Delete(T Item);
    void Attach(T Item);
    void Update(T Item);
    int Count();
}

我的问题是我正在尝试测试一种使用getById()的方法,但是可以通过IUnitOfWork对象访问该方法,如下所示:

My issue is that I'm trying to test a method that makes use of getById(), however this method is accessed through an IUnitOfWork object, like this:

public static TestRun getTestRunByID(IUnitOfWork database, int testRun)
{
    TestRun testRun = database.TestRunsRepo.getByID(testRun);
    return testRun;
}

在我的测试中,我嘲笑了两件事; IUnitOfWorkIRepository.我已经配置了IRepository,以便它返回TestRun项,但是我实际上不能使用此存储库,因为在getTestRunByID()方法中,它从IUnitOfWork对象获取了自己的存储库.结果,这导致NullReferenceException.

In my test I have mocked 2 things; IUnitOfWork and IRepository. I have configured the IRepository so that it returns a TestRun item, however I can't actually make use of this repo since in the getTestRunByID() method it gets its own repo from the IUnitOfWork object. As a result this causes a NullReferenceException.

我尝试将我的仓库添加到IUnitOfWork的仓库中,但是由于所有仓库都标记为{get; } 只要.我的测试是:

I have tried adding my repo to the IUnitOfWork's repo but it will not compile since all repos are marked as { get; } only. My test is:

[TestMethod]
public void GetTestRunById_ValidId_TestRunReturned()
{
    var mockTestRunRepo = new Mock<IRepository<TestRun>>();
    var testDb = new Mock<IUnitOfWork>().Object;
    TestRun testRun = new TestRun();
    mockTestRunRepo.Setup(mock => mock.getByID(It.IsAny<int>())).Returns(testRun);

    //testDb.TestRunsRepo = mockTestRunRepo; CAN'T BE ASSIGNED AS IT'S READ ONLY

    TestRun returnedRun = EntityHelper.getTestRunByID(testDb, 1);     
}

如何获取我的IUnitOfWork's存储库以不抛出NullReferenceException?

How can I get my IUnitOfWork's repo to not throw a NullReferenceException?

推荐答案

您无法分配给模拟,需要通过安装程序配置属性.

You can't assign to a mock, you need to configure the properties via a Setup.


代替:

testDb.TestRunsRepo = mockTestRunRepo;

尝试:

testDb.Setup(m => m.TestRunsRepo).Returns(mockTestRunRepo.Object);

testDb.SetupGet(m => m.TestRunsRepo).Returns(mockTestRunRepo.Object);

这篇关于模拟{get; }(Moq)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆