【问题标题】:Mocking an interface which is { get; } only (Moq)模拟 { get; 的接口} 仅(起订量)
【发布时间】:2016-01-14 12:01:13
【问题描述】:

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

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

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

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

我尝试将我的 repo 添加到 IUnitOfWork 的 repo,但它不会编译,因为所有 repo 都标记为 { 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

【问题讨论】:

    标签: c# unit-testing moq


    【解决方案1】:

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


    代替:
    testDb.TestRunsRepo = mockTestRunRepo;
    

    试试:

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

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

    【讨论】:

    • 成功了!非常感谢您的帮助(再次!):) 我没想到要从我的 IUnitOfWork 返回一个 repo,干杯
    【解决方案2】:

    我想你会想要这样的安排:

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

    当设置模拟并让它返回你想要的东西要容易得多时,你正试图为模拟对象分配一些东西。

    【讨论】:

    • 这不起作用n.TestRunsRepo() 建议一个方法,这是一个属性。需要n.TestRunsRepo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2016-08-25
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多