Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq internal class and/or internal method

Tags:

c#

moq

.net-4.6.1

On my project, I set:

[assembly: InternalsVisibleTo("xyz")]

My unit tests work when my class and method are public.

public class MainController
{
    public virtual void RunForm()
    {
        ...
    }

If I change either to internal, my unit test fails. Is this a limitation of Moq?

var logger = new Mock<IExceptionLogger>();
var name = new Mock<MainController>
{
    CallBase = true
};
name.Setup(x => x.RunForm()).Throws(new Exception()));
name.Object.Init(logger.Object);
logger.Verify(m => m.LogError(It.IsAny<Exception>(), Times.Once);

Exception:

Test method Tests.Controllers.MainControllerTest.ExceptionsInitGetLoggedToAppInsights threw exception: 
    System.ArgumentException: Cannot set up MainController.RunForm because it is not accessible to the proxy generator used by Moq:
    Can not create proxy for method Void RunForm() because it or its declaring type is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute, because assembly Abc is not strong-named.
like image 906
Hoppe Avatar asked Aug 19 '26 18:08

Hoppe


1 Answers

As stated in the error message, you actually need to add the [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute to your assembly. DynamicProxyGenAssembly2 is the assembly that Moq uses internally to create the proxy instances of your class to override/implement virtual/interface methods.

like image 63
devNull Avatar answered Aug 22 '26 00:08

devNull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!