模拟接口 { get; } 只有(最小起订量)

Mocking an interface which is { get; } only (Moq)

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

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

我们的 IRepository class 看起来像这样:

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 对象访问的,如下所示:

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

在我的测试中,我模拟了两件事; IUnitOfWorkIRepository。我已经配置了 IRepository 以便它 returns 一个 TestRun 项目,但是我实际上不能使用这个 repo,因为在 getTestRunByID() 方法中它有自己的 repo来自 IUnitOfWork 对象。结果,这导致 NullReferenceException

我已经尝试将我的存储库添加到 IUnitOfWork 的存储库中,但它无法编译,因为所有存储库都被标记​​为 { get; } 只要。我的测试是:

[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

您不能分配给模拟,您需要通过设置配置属性。


而不是:

testDb.TestRunsRepo = mockTestRunRepo;

尝试:

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

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

我想你会想要这样的东西:

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

您正试图将某些东西分配给模拟对象,而仅设置模拟并让其 return 成为您想要的东西要容易得多。