I have a Visual Studio 2008 C# .NET 3.5 project that I am implementing unit tests for, but I’ve run in to a problem. My code references a 3rd party assembly that implements objects with internal constructors.
For example:
// in 3rd party assembly
public class Bar
{
// internal constructor
internal Bar();
public int Id { get; }
public string Name { get; }
public Foo Foo { get; }
}
public class Foo
{
// internal constructor
internal Foo();
public Collection<Bar> GetBars();
}
One method of mine that I would like to unit test is this:
// in my assembly
public static Bar FindByName(this Collection<Foo> c, string name)
{
// search through the Foos to find the first bar with the matching name
}
And test it like this:
void TestMethod()
{
Collection<Foo> foo_pool = new Collection<Foo>()
{
new Foo() { /*..*/ } // Error! ctor is inaccessible
};
Bar b = foo_pool.FindByName("some_name");
assert_equal (b.Name, "some_name");
}
But, I can’t create objects of type Foo or type Bar. So, how can I unit test my method?
Thanks
For unit tests, you can use the PrivateObject class (namespace Microsoft.VisualStudio.TestTools.UnitTesting) to create objects with private constructors and even test private methods.
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject(v=vs.90).aspx
http://www.gangleri.net/2007/11/15/PrivateObjects.aspx
Here’s an example:
It uses reflection in the same way as Jim’s suggestion, but PrivateObject class encapsulates all the work to create the instance with private constructors.