简体   繁体   English

MOQ验证执行无效

[英]MOQ verify for execution doens't work

I'm trying to mock my internal virtual method. 我正在尝试模拟我的内部虚拟方法。 When I debug I can see I get to where I expect and my internal virtual method is exceuted but the test fails. 调试时,可以看到我所期望的位置,内部虚拟方法已执行,但测试失败。 Further more, I verified 'this' context is the proxy and not a regular class instance. 此外,我验证了“此”上下文是代理而不是常规类实例。

Methods: 方法:

public void MyMethod() { MyInternalMethod() }
internal virtual void MyInternalMethod() {}

Piece of unit test: 一块单元测试:

Because of = () => { myMock.Object.MyMethod() };

It should_run_inner_internal_virtual_MyInternalMethod = () =>
{
              myMock.Verify(x => x.MyInternalMethod(),Times.Once());
};

I'll appreciate any help. 我将不胜感激。

Kind regards. 亲切的问候。

Am not sure if your code compiles, but I think since Moq and the class under test are in different assemblies, you may need to tell the assembly of the object under test to make internal visible to the Moq's assembly. 不确定代码是否可以编译,但是我认为由于Moq和被测类位于不同的程序集中,因此您可能需要告诉被测对象的程序集以使内部对Moq的程序可见。 internal only makes a method / property / class visible to that assembly. internal仅使该程序集可以看到方法/属性/类。

Try adding this to your AssemblyInfo.cs file (for the assembly under test) 尝试将其添加到AssemblyInfo.cs文件中(对于被测程序集)

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] 

assuming DynamicProxyGenAssembly2 is your Moq's assembly name. 假设DynamicProxyGenAssembly2是Moq的程序集名称。 If your test is also in a different assembly, then you need to make the internals visible to that assembly as well. 如果您的测试也位于不同的程序集中,那么您还需要使内部对于该程序集也可见。 I just wrote a nunit test for this, and it passes. 我刚刚为此编写了一个nunit测试,它通过了。

[Test]
public void ShouldCallMyInternalMethodFromMyMethod()
{
  myMock = new Mock<MyClass>();
  myMock.Object.MyMethod();
  myMock.Verify(mockObj=> mockObj.MyInternalMethod(), Times.Once());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM