最小起订量单元测试 - 预期结果?

Moq Unit Testing - expected result?

我正在使用 Moq 进行单元测试,并获得了以下方法:

[TestMethod]
public void GetTestRunById_ValidId_TestRunReturned()
{
    var mockTestRunRepo = new Mock<IRepository<TestRun>>();
    var testDb = new Mock<IUnitOfWork>();

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

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

正在测试的相关方法是 getTestRunByID()。我已经确认在调试此单元测试时会调用此方法,但正如预期的那样,getTestRunByID() 不会 return 任何内容,因为模拟中没有数据。

重要的是方法被命中并且 return 为空吗?如果没有,当它仅作为来自 testDb 的 returned 值存在时,我如何将数据添加到我的 mockTestRunRepo?

供参考,正在测试的方法是:

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

您拥有存储库 return 数据的方式与设置其他所有内容的方式相同。

var mockTestRunRepo = new Mock<IRepository<TestRun>>();

// This step can be moved into the individual tests if you initialize
// mockTestRunRepo as a Class-level variable before each test to save code.
mockTestRunRepo.Setup(m => m.getById(1)).Returns(new TestRun());

根据@Sign 的建议,如果您知道您使用 1 调用它,那么使用它而不是 It.IsAny<int>() 以保持清洁。

单元测试的目的是只测试小方法getTestRunByID。为此,测试是否使用整数参数 1 恰好调用了一次。

mockTestRunRepo.Verify(m => m.getByID(1), Times.Once());

你还必须为mockTestRunRepo设置方法getByID,使其return成为一个特定的值,并测试测试的结果值是否运行等于你的预期。

//instantiate something to be a TestRun object.
//Not sure if abstract base class or you can just use new TestRun()
mockTestRunRepo.Setup(m => m.getByID(1)).Returns(something);

测试是否得到相同的值

TestRun returnedRun = EntityHelper.getTestRunByID(testDb.Object, 1);
Assert.AreEqual(returnedRun, something);

这段代码可能容易出错,因为我现在没有测试它的环境。但这是单元测试背后的一般思想。

这样,您可以测试方法 getById 运行 是否符合预期,return 是否符合预期结果。