My Software Notes

Useful things I discover

Archive for the ‘Testing’ Category

Unit Testing Non-Public Methods in .NET

leave a comment »

Just a note to self on how to test non-public methods.

Internal methods can be accessed using the InternalsVisibleTo attribute in AssemblyInfo.cs.

        [assembly: InternalsVisibleTo("MyAssembly.Tests")]

There is a little more needed for signed assemblies. Check out this reference: Unit Test Non-Public Methods and Classes.

For private (not sure if this applies to protected or not) use the PrivateObject Class.

Example: test a method that reverses a string. Method signature:

        private string ReverseIt(string forward)

Example code:

            var expected = "drawroF";
            var testValue = "Forward";
            var example = new ExampleClass();
            var testObj = new PrivateObject(example);
            var actual = testObj.Invoke("ReverseIt", testValue);
            Assert.AreEqual(expected, actual);

A protected method is easy to test by creating a subclass of the class.

Advertisements

Written by gsdwriter

November 28, 2017 at 1:59 pm

Posted in .NET, Testing

How to Unit Test Custom Data Annotations

with one comment

I created a custom data annotation to test a zip code and I started writing a unit test to make sure it worked and … ehhh, ummm, arrr?? How do I test it?

Well, I searched and found this great article: Unit Testing Custom Data Annotations.

Thank you Walter C. Johnson! A nice clean solution.

Written by gsdwriter

December 16, 2011 at 5:42 pm

Posted in .NET, Testing, Tools

Tagged with ,