一个非虚拟(VB中重写)成员设置无效 [英] Invalid setup on a non-virtual (overridable in VB) member

查看:443
本文介绍了一个非虚拟(VB中重写)成员设置无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元测试,在那里我有嘲笑一个返回bool类型

I have a unit test where i have to mock a non-virtual method that returns a bool type

public class XmlCupboardAccess
{
 public bool IsDataEntityInXmlCupboard(string dataId,
                                          out string nameInCupboard,
                                          out string refTypeInCupboard,
                                          string nameTemplate = null)
    {
        return IsDataEntityInXmlCupboard(_theDb, dataId, out nameInCupboard, out refTypeInCupboard, nameTemplate);
    }
}



所以我有XmlCupboardAccess类和我的模仿对象我想设置模拟在我的测试情况下,这种方法如下图所示。

So i have a mock object of XmlCupboardAccess class and i am trying to setup mock for this method in my test case as shown below

[TestMethod]
Public void Test()
{
  private string temp1;
  private string temp2;
  private Mock<XmlCupboardAccess> _xmlCupboardAccess = new Mock<XmlCupboardAccess>();
  _xmlCupboardAccess.Setup(x => x.IsDataEntityInXmlCupboard(It.IsAny<string>(), 
  out temp1, out temp2, It.IsAny<string>())).Returns(false); 
  //exception is thrown by this line of code
}



但这种甩行抛出异常。

But this line throws exception

Invalid setup on a non-virtual (overridable in VB) member: 
x => x.IsDataEntityInXmlCupboard(It.IsAny<String>(), .temp1, .temp2, 
It.IsAny<String>())

任何建议如何得到这个例外在吗?

Any suggestion how to get around this exception?

推荐答案

起订量不能模拟非虚拟方法和密封类。在使用mock对象运行测试,起订量实际上创建从你的XmlCupboardAccess继承并重写你已经在设置的方法设立行为在内存中的代理类型。而当你在C#中知道,你可以覆盖只有当它被标记为虚拟这是不是与Java的情况下的东西。 Java的假定每一个非静态方法是在默认情况下虚拟的。

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

另外一点我相信你应该考虑的是引入一个界面为你CupboardAccess,并开始嘲讽接口而不是。这将帮助你解耦你的代码,并有更长远的利益。

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

最后,有喜欢的框架:的 TypeMock JustMock 它与IL直接合作因此可以模拟非虚方法。但是两者都是商业产品。

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

这篇关于一个非虚拟(VB中重写)成员设置无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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