23

我是 Moq 和一般测试的新手,所以这是我的菜鸟问题。我如何测试请求上的Status属性是否已使用 Moq 设置?

public class DudeManager
{
        private readonly IDRepository _repo;

        public DManager(IDRepository repo)
        {
            _repo = repo;
        }

        public void Create(Request r)
        {
            r.Status = Status.Submitted;
            _repo.AddRequest(r);
        }
}

有比以下更好的方法吗?也许使用验证集?

        [TestMethod]
        public void AddingNewRequestSetsStatusToSubmitted()
        {
            //Arrange
            var mock = new Mock<IDRepository>();
            var mockRequest = new Mock<Request>();
            var dManager = new DManager(mock.Object);

            //Act
            dManager.Create(mockRequest.Object);

            //Assert
            Assert.AreEqual(Status.Submitted, mockRequest.Object.Status);
        }

编辑:这是我在所有有用的建议之后最终使用的方法:

//Arrange
var request = new Request();
var mock = new Mock<IDRepository>();
var dManager = new DManager(mock.Object);
mock.Setup(x => x.AddRequest(It.IsAny<Request>()));

//Act
dManager.QueueNewRequest(request);

//Assert
Assert.AreEqual(RequestStatus.Submitted, request.Status);

这种方法对我来说似乎是正确的。有人不这么认为吗?

4

3 回答 3

37

我认为 VerifySet 是正确的方法。它看起来像这样:

//Arrange
var mock = new Mock<IDRepository>();
var mockRequest = new Mock<Request>();
// TODO: set some expectations here

var dManager = new DManager(mock.Object);

//Act
dManager.Create(mockRequest.Object);

//Assert
mockRequest.VerifySet(x => x.Status = Status.Submitted);

我相信在你的情况下,它会爆炸,因为你没有设置你的请求模拟来处理状态上的设置操作。

一种简单的方法是使用SetupAllProperties,如下所示:

//Arrange
var mock = new Mock<IDRepository>();
var mockRequest = new Mock<Request>();
mockRequest.SetupAllProperties();
于 2013-06-04T21:16:05.977 回答
7

我认为您应该默认使用严格的行为,然后您可以通过一次调用进行验证。它还使您可以更明确地编写测试。

[TestMethod]
public void AddingNewRequestSetsStatusToSubmitted()
{
    //Arrange
    var mock = new Mock<IDRepository>(MockBehavior.Strict);
    var mockRequest = new Mock<Request>(MockBehavior.Strict);
    var dManager = new DManager(mock.Object);

    mockRequest.SetupSet(item => item.Status = It.IsAny<StatusType>())
               .Verifiable();

    //Act
    dManager.Create(mockRequest.Object);

    //Assert
    Assert.AreEqual(mockRequest.Object.Status, Status.Submitted);
    mock.VerifyAll();
    mockRequest.VerifyAll();
}
于 2013-06-04T21:41:23.587 回答
4
mock.Verify(m=>m.AddRequest(It.Is<Request>(r=>r.Status == expectedStatus)));

您可以验证是否使用具有正确的参数 ()AddRequest调用该方法。此外,这里并不需要模拟对象。RequestStatusRequest

于 2013-06-04T22:45:25.430 回答