ASP.Net - MVC and Moq
I'm starting to build up Unit Tests for a project we have. We've decided upon开发者_开发知识库 Moq to assist with the 'Mocking' of the repositorys as we dont want to run the tests against the live DB.
I'm obviously using Moq incorrectly, How would one write the GetMessage Test? The first 2 seem to work fine.
The return value of the GetMessage Test is allways null so the test fails
private Mock<IMessageRepository> _mockRepository;
private IMessageBoardService _service;
[TestInitialize]
public void Initialize()
{
_mockRepository = new Mock<IMessageRepository>();
_service = new MessageBoardService(_mockRepository.Object);
}
[TestMethod]
public void CreateMessage()
{
var result = _service.CreateMessage("Test", "Description", 8000, 0);
Assert.IsNotNull(result);
}
[TestMethod]
public void CreateComment()
{
var Message = _service.CreateMessage("Test", "Description", 8000, 0);
var Result = _service.CreateComment("Test Comment", Message.MessageID, 0);
Assert.IsNotNull(Result);
}
[TestMethod]
public void GetMessage()
{
var Message = _service.CreateMessage("Test", "Description", 8000, 0);
_service.AddMessage(Message);
_service.Save();
var RetMessage = _service.GetMessage(Message.MessageID); //Always returns Null
Assert.IsNotNull(RetMessage);
}
EDIT= == ===============================
What about the following?
[TestMethod]
public void GetMessage()
{
var tmpMessage = _service.CreateMessage("Test", "Description", 5, 0);
_mockRepository.Setup(r => r.GetMessage(It.IsAny<int>()))
.Returns(tmpMessage);
var RetMessage = _service.GetMessage(tmpMessage.MessageID);
Assert.IsNotNull(RetMessage);
}
You need to set an expectation for you mock. Something like:
[TestInitialize]
public void Initialize()
{
_mockRepository = new Mock<IMessageRepository>();
_mockRepository.Setup(r=> r.GetMessage())
.Returns(8000); // I assume 8000 is message Id in test
_service = new MessageBoardService(_mockRepository.Object);
}
I have assumed that your repository has a GetMessage that the Service uses. It is the method that the service uses that needs to be mocked.
This will be done for all uses of this mock. For that reason I would set it up in the individual test rather than initialize. I just wanted to highlight you need an expectation.
Kindness,
Dan
It might be better to setup the Stub so that you verify that the correct message ID is being passed to the repository's method:
[TestMethod]
public void GetMessage()
{
var tmpMessage = _service.CreateMessage("Test", "Description", 5, 0);
_mockRepository.Setup(r => r.GetMessage(tmpMessage.MessageID))
.Returns(tmpMessage);
var RetMessage = _service.GetMessage(tmpMessage.MessageID);
Assert.AreEqual(tmpMessage, RetMessage);
}
Notice that I have also modified the assertion so that it verifies what you are likely to care about: that the returned value is correct (and not just whether it's null or not).
精彩评论