Search code examples
c#unit-testingaccess-modifiersinternalsvisibleto

Does a [TestMethod] have to be public? What consequences are there if it isn't?


I am using the test facilities provided by Microsoft.VisualStudio.TestPlatform.TestFramework. I have a test method decorated with [TestMethod]. I want to implement this test for various combinations of parameters using [DataRow]. One of the parameters that the method will need is an enum type declared as internal in another assembly; the assembly in which the enum type is defined gives the assembly containing the unit tests access to its internals via InternalsVisibleTo.

Unit test methods are conventionally public within a public class, so far as I can tell. When it comes to this unit test method, either the test method must be inaccessible from outside the unit test assembly (achieved by making it private or internal, or by making the test class that contains it internal) or the enum must be made public. Making the enum public would be inappropriate, so it would appear correct to make the test method internal.

Are there any possible negative consequences to making the unit test method internal?

This question is doubtless a simple one that has a simple answer. I am asking it because I am having no success at all searching the internet for an answer to it. All I can locate are discussions about whether one should test private methods or not.

Note: If you give a comment or answer that fails to answer my question but instead suggests or implies that it's wrong to test internal members of an assembly using InternalsVisibleTo, then I shall reject your answer out of hand.

Note 2: One possible thing to be done in this case is to use a string parameter instead of the enum parameter, use Enum.Parse in the test method, and pass all of the relevant parameters as strings constructed using the nameof operator. I don't like this, but it might be the least bad workaround.


Solution

  • At least for MSTest, the test runner in visual studio won't detect methods that aren't public when run. Here's a quick sample.

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1() => Assert.IsTrue(true);
    
        [TestMethod]
        internal void TestMethod2() => Assert.IsTrue(false);
    }
    

    Results are that one test was detected, run, and passed. So I would consider that a major negative consequence to not having the test methods public.