Help with this unit test using Moq

旧时模样 提交于 2019-12-23 03:16:01

问题


I have the following so far which I am trying to unit test:

private Mock<IDBFactory> _mockDbFactory;
private IArticleManager _articleManager;

[Setup]
public Setup()
{
      _mockDbFactory = new Mock<IDBFactory>();

      _articleManager = new ArticleManager(_mockDbFactory);
}



[Test]
public void load_article_by_title()
{
    string title = "sometitle";

    // _dbFactory.GetArticleDao().GetByTitle(title);  <!-- need to mock this

    _mockDBFactory.Setup(x => x.GetArticleDao().GetByTitle(It.IsAny<string>()));

    _articleManager.LoadArticle(title);

    Assert.IsNotNull(_articleManager.Article);

}

I get the error:

Invalid setup of a non-overridable member:


回答1:


You need to provide a mock for the object returned by GetArticleDao. Something like this:

var _mockDao = new Mock<IArticleDao>();
_mockDao.Setup(x => x.GetByTitle("test")).Returns("A test title");
_mockDBFactory.Setup(x => x.GetArticleDao).Returns(_mockDao);

The syntax is from memory so it may be off. If GetByTitle returns an object you will need to provide a mock implementation for it as well.



来源:https://stackoverflow.com/questions/1961778/help-with-this-unit-test-using-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!