最小起订量:不可覆盖成员上的无效设置:x =>x.GetByTitle("asdf") [英] Moq: Invalid setup on a non-overridable member: x => x.GetByTitle("asdf")

查看:20
本文介绍了最小起订量:不可覆盖成员上的无效设置:x =>x.GetByTitle("asdf")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定如何解决此问题,尝试对GetByTitle"方法进行单元测试

Not sure how I can fix this, trying to do a unit test on the method "GetByTitle"

这是我的定义:

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);
}

单元测试:

[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);
}

运行测试给了我错误:

System.ArgumentException: Invalid setup on a non-overridable member:
x => x.GetByTitle("some title")

更新

我的 [Setup] 看起来像:

[Setup]
public void SetUp()
{
     _mockDaoFactory = new Mock<IDaoFactory>();
     _mockArticleDao = new Mock<ArticleDao>();

     _articleManager = new ArticleManager(_mockDaoFactory.Object);    
}

推荐答案

为了控制模拟对象的行为(至少在 Moq 中),你要么需要模拟一个接口,要么确保你的行为'试图控制被标记为虚拟.在你的评论中,我理解它是这样的,_mockArticleDao 的实例化是这样完成的:

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:

_mockArticleDao = new Mock<ArticleDAO>();

如果要保持原样,需要标记GetArticle方法virtual:

If you want to keep it as so, you need to mark the GetArticle method 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>();

这篇关于最小起订量:不可覆盖成员上的无效设置:x =>x.GetByTitle("asdf")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆