肯定有一些明显的我忽略了 - 通常当我遇到这样的问题时。
我有一个控制器,它只是根据提供的 ID 返回一篇新闻文章:
[HandleError]
public class HomeController : Controller
{
private readonly IArticleRepository articleRepository;
public HomeController(IArticleRepository Repository)
{
articleRepository = Repository;
}
public ActionResult Index()
{
return View("Index");
}
// Here's the bit we're interested in
public ActionResult Article(int id)
{
var article = articleRepository.GetById(id);
return View("Article", article);
}
}
我像这样使用 Moq 来模拟这个:
[TestFixture]
public class HomeControllerTests
{
HomeController controller;
int articleId;
Article model;
[TestFixtureSetUp]
public void SetupMethods()
{
Mock<IArticleRepository> repositoryMock = new Mock<IArticleRepository>();
repositoryMock.Setup(x => x.GetById(articleId)).Returns(GetSampleArticle());
controller = new HomeController(repositoryMock.Object);
}
[Test]
public void Article_Action_Returns_Requested_Article()
{
// Arrange
model = new Article();
articleId = 1;
// Act
ActionResult result = controller.Article(articleId);
// Assert
var viewResult = ((ViewResult)result);
var returnedModel = viewResult.Model;
Assert.IsInstanceOf<Article>(viewResult.Model);
//Assert.AreEqual(articleId, returnedModel.ID);
}
}
上面有问题的“GetSampleArticle”方法看起来像这样:
private Article GetSampleArticle()
{
Article article = new Article()
{
Archived = false,
Body = "<p>This is a dummy sample article for use in our mocks.</p>",
EndDate = DateTime.Today.AddDays(30),
ID = 1,
Priority = 3,
StartDate = DateTime.Today,
Title = "Sample Article"
};
return article;
}
但是我仍然得到模型的空类型。那么我忘记了什么?
News.Tests.Controllers.HomeControllerTests.Article_Action_Returns_Requested_Article:
Expected: instance of <News.Data.Article>
But was: null