user1429595
user1429595

Reputation: 2735

How to call public static methods in Unit Test

Hi I have a simple method as following and need to know how I can call it in Unit Test in Visual Studio

 public class myClass
 {
     public static bool Test(string value, string regex)
     {
         if (Regex.IsMatch(value, regex, RegexOptions.IgnoreCase))
             return true;

         return false;
     }
 }

here is what I have sofar

 [TestMethod]
 public void TestMethod_Test()
 {
     string value = "myValue";
     string regex = "&#@<>\s\\\$\(\)";

     PrivateType pt = new PrivateType(typeof(myClass));
     bool actualresult = (bool)pt.InvokeStatic("Test", new object[] { value, regex });
     bool expectedResult = false;
     Assert.AreEqual(actualresult, expectedResult);

 }

Upvotes: 3

Views: 3958

Answers (2)

jessehouwing
jessehouwing

Reputation: 114461

If both the method and the class are public, then you could simply call

myClass.Test(value, regex);

If myClass is protected you could do:

public myClassWrapper : myChild
{ 
    public static bool Test(string text, string regex)
    {
        return myClass.Test(text, regex);
    }
}

If myClass is internal or 'default' (no visibility specified, which seems to be your case) you can make make the assembly that contains myClass friendly towards the test library by adding an InternalsVisisbleTo attribute to it:

[assembly:InternalsVisibleTo("myClassLibrary")]

That way your test project should be able to just invoke the Test Method directly as if it were public.

If the class is not public or you cannot alter the definition of the class, consider finding a method that internally uses the method you want to test and use that to verify the behavior. (e.g. test that the method that uses the Test method works correctly, thereby you test that the Test method works correctly.

Upvotes: 2

David Arno
David Arno

Reputation: 43254

You do not want to be using reflection. Just call the method directly:

[TestMethod]
public void TestMethod_Test()
{
    string value = "myValue";
    string regex = "&#@<>\s\\\$\(\)";

    var result = ClassContainingTest.Test(value, regex); 
    Assert.AreEqual(false, result);
}

If ClassContainingTest isn't public, then it isn't sensible to be trying to unit test Test. Only test publicly accessible functionality.

Upvotes: 5

Related Questions