C# 最小起订量:不可覆盖成员上的无效设置:x => x.GetByTitle("asdf")
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1962010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moq: Invalid setup on a non-overridable member: x => x.GetByTitle("asdf")
提问by mrblah
Not sure how I can fix this, trying to do a unit test on the method "GetByTitle"
不知道如何解决这个问题,尝试对方法“GetByTitle”进行单元测试
Here are my definitions:
以下是我的定义:
public class ArticleDAO : GenericNHibernateDAO(IArticle, int>, IArticleDAO
{
public IArticle GetByTitle(string title)
{
IQuery query = Session.CreateQuery("...")
return query.UniqueResult<IArticle>();
}
}
public interface IArticleDAO
{
IArticle GetByTitle(string title);
}
unit test:
单元测试:
[Test]
public void can_load_by_title()
{
_mockDaoFactory.Setup(x => x.GetArticleDao())
.Returns(_mockArticleDao.Object);
_mockArticleDao.Setup(x => x.GetByTitle("some title"))
.Returns(article1.Object);
_articleManager.LoadArticle("some title");
Assert.IsNotNull(_articleManager.Article);
}
Running the test gives me the error:
运行测试给了我错误:
System.ArgumentException: Invalid setup on a non-overridable member:
x => x.GetByTitle("some title")
Update
更新
My [Setup]
looks like:
我的[Setup]
样子:
[Setup]
public void SetUp()
{
_mockDaoFactory = new Mock<IDaoFactory>();
_mockArticleDao = new Mock<ArticleDao>();
_articleManager = new ArticleManager(_mockDaoFactory.Object);
}
回答by Tomas Aschan
In order to control the behavior of a mock object (in Moq, at least), you either need to mock an interface, or make sure that the behavior you're trying to control is marked virtual. In your comment, I understand it so that the instantiating of _mockArticleDao
is done something like this:
为了控制模拟对象的行为(至少在 Moq 中),您要么需要模拟接口,要么确保您尝试控制的行为被标记为虚拟。在您的评论中,我理解它的实例化_mockArticleDao
是这样完成的:
_mockArticleDao = new Mock<ArticleDAO>();
If you want to keep it as so, you need to mark the GetArticle
method virtual
:
如果要保持原样,则需要标记GetArticle
方法virtual
:
public class ArticleDAO : GenericNHibernateDAO(IArticle, int>, IArticleDAO
{
public virtual IArticle GetByTitle(string title)
{
// ...
}
}
Otherwise (and this is what I recommend), mock the interface instead.
否则(这是我推荐的),而是模拟界面。
_mockArticleDao = new Mock<IArticleDAO>();