How to write unit test for private method in C # using moq framework?

I want to write unit test for a private method in C # using the moq framework, I am looking at StackOverFlow and Google, but I can not find the expected result. Please help me if you can.

+5
source share
4 answers

You cannot, at least not using Moq.

But more importantly, you should not. First, you do not test methods; you test behavior. Secondly, to test the behavior, you implement a public type API and check the results of this exercise.

Private methods are implementation details. You do not want to check how everything is done, you want to check that everything is done.

+23
source

In AssemblyInfo.cs of your project add

[assembly: InternalsVisibleTo("Namespace.OfYourUnitTest.Project")] 

you will make the method internal, not private.

This makes it possible to avoid publicity.

However, as dcastro pointed out, some people strongly disagree with this testing method.

+4
source

Simply no. Private methods are not visible to other classes.

There are several ways:

  • Treat private as part of the method you are testing, cover it in your unit tests. Think of public methods as black boxes and test their operations.
  • Make it secure and inherit your test class from the class you are testing (or use a partially-same idea)
  • Make it publicly available (which, if you code the interface, doesn't actually reveal it to your consumers)

For public methods (option three), you can partially mock a class where you can replace this method. In Moq, you can do it like this:

 var moq = new Mock<MyClass>(); moq.CallBase = true; moq.Setup(x => x.MyPublicMethodToOverride()).Returns(true); 

More details here .

+3
source

You probably shouldn't (see other answers why), but you can do it using Microsoft Visual Studio Test Tools . The following is a simplified example.

Given the following class you want to test:

 public class ClassToTest { private int Duplicate(int n) { return n*2; } } 

You can use the following code to test the private Duplicate method:

 using Microsoft.VisualStudio.TestTools.UnitTesting; // ... [TestMethod] public void MyTestMethod() { // Arrange var testClass = new ClassToTest(); var privateObject = new PrivateObject(testClass); // Act var output = (int) privateObject.Invoke("Duplicate", 21); // Assert Assert.AreEqual(42, output); } 
+3
source

Source: https://habr.com/ru/post/1200006/


All Articles