到目前为止,我有以下内容,我正在尝试进行单元测试:
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);
}
我收到错误:
无法覆盖的成员的设置无效:
答案 0 :(得分:2)
您需要为GetArticleDao返回的对象提供模拟。像这样:
var _mockDao = new Mock<IArticleDao>();
_mockDao.Setup(x => x.GetByTitle("test")).Returns("A test title");
_mockDBFactory.Setup(x => x.GetArticleDao).Returns(_mockDao);
语法来自内存,因此它可能已关闭。如果GetByTitle返回一个对象,你也需要为它提供一个模拟实现。