我是Moq的新手和一般的测试所以这是我的noobish Q. 如何测试是否已使用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);
}
}
有没有比以下更好的方法?也许使用VerifySet?
[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);
这种方法对我来说似乎是对的。有人不这么想吗?
答案 0 :(得分:28)
我认为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);
我相信你的情况,它会爆炸,因为你还没有设置你的Request模拟来处理Status上的设置操作。
一种简单的方法是使用SetupAllProperties
,如下所示:
//Arrange
var mock = new Mock<IDRepository>();
var mockRequest = new Mock<Request>();
mockRequest.SetupAllProperties();
答案 1 :(得分:6)
我认为您应该默认使用严格的行为,然后您可以通过一次调用进行验证。它还可以让您更明确地编写测试。
[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();
}
答案 2 :(得分:4)
mock.Verify(m=>m.AddRequest(It.Is<Request>(r=>r.Status == expectedStatus)));
您可以验证是否使用具有正确AddRequest
的参数(Request
)调用Status
方法。此外,在这里不需要模拟Request
对象。