The aim: write a comprehensive suite of unit tests for a library we are creating.
Create a library project named Lib, which contains a class named StrExt, which contains a public method Tidy and an internal method IsBad. The implementation is as follows ...
namespace Lib { public class StrExt { public string Tidy(string s) { if (IsBad(s) == false) return s.Trim(); else return null; } internal bool IsBad(string s) { return s == null; } } }To test the above class, create a test project, call it Lib.Tests. In it, create the following test method to test the public method Tidy(string)...
[TestMethod] public void Tidy_ReturnsCorrectValue() { string inStr = "test "; string expOutStr = "test"; string actualOutStr = lib.Tidy(inStr); Assert.AreEqual(expOutStr, actualOutStr); }This will work fine.
But what if we wanted to (and we should) test the internal method IsBad(string). Notice that the intellisense in the capture below does not display IsBad. This is obviously because the method IsBad, is declared internal to the Lib assembly and is therefore not visible to other assemblies such as Lib.Tests.

Writing tests for internal methods is a very common scenario. People often use convoluted techniques like Reflection etc to invoke the internal method. An easier and the correct solution is to use InternalsVisibleToAttribute as follows ...
using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute("Lib.Tests")] namespace Lib { public class StrExt { ... /* No change in this class */ } }This makes the internal methods of the class visible to the named assembly. Now notice the intellisense ...
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Lib { [TestClass] public class Lib_UnitTests { private StrExt lib = new StrExt(); [TestMethod] public void Tidy_ReturnsCorrectValue() { string inStr = "test "; string expOutStr = "test"; string actualOutStr = lib.Tidy(inStr); Assert.AreEqual(expOutStr, actualOutStr); } [TestMethod] public void IsBad_ReturnsTrueForNullString() { string inStr = null; bool result = lib.IsBad(inStr); Assert.IsTrue(result); } } }Look ma, no reflection!


0 comments:
Post a Comment