Help with this unit test using Moq

2019-06-04 01:42发布

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:

标签: c# nunit moq
1条回答
太酷不给撩
2楼-- · 2019-06-04 02:29

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.

查看更多
登录 后发表回答