expected result?

I'm using Moq for my Unit Tests and have got the following method:

[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);
}

The method in question which is being tested is getTestRunByID(). I have confirmed that this method is called when debugging this unit test, but as expected getTestRunByID() doesn't return anything since the mock has no data inside it.

Would all that matter is the method gets hit and returns null? If not, how can I add data to my mockTestRunRepo when it's only present as a returned value from testDb?

For reference the method being tested is:

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

The purpose of the unit test is to ONLY test the small method getTestRunByID . For that, test if it was called exactly once with that integer parameters, 1 .

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

You must also set up the method getByID for mockTestRunRepo , to make it return a specific value, and test if the result value of the test run is equal to what you expected.

//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);

Test if you get the same value

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

This code might be prone to errors, as I do not have an environment to test it right now. But this is the general idea behind a unit test.

This way, you test if the method getById runs as expected, and returns the expected result.


You have your repository return data the same way that you setup everything else.

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());

Per @Sign's recommendation, if you know that you're calling it with 1 , then use that instead of It.IsAny<int>() to keep things cleaner.

链接地址: http://www.djcxy.com/p/35344.html

上一篇: 问题与单元测试嘲讽Moq

下一篇: 预期结果?