Hey evryone
All the stuff I've read says you should unit test the public interface of your classes. I'm a little confused as to how I should be testing classes that are derived from EventArgs.
EventArgs classes are public, which makes me think they should be tested like any other public class so I can verify their behavior, but I'm finding this difficult to do because although the classes are publicly exposed, their constructors are all internal,
which makes writing unit tests difficult.
How does one go about testing the public members on a class with no public constructors?
I could use #define or the Debug attribute to expose the constructors on debug buids, but thats kinda messy.
-
-
Hi, you could go with reflection. The following sample shows how to create an instance of a class by using the Activator class (which uses reflection:
class Program
{
static void Main(string[] args)
{
// Create an instance of the class by using reflection
FooEventArgs ea = (FooEventArgs)Activator.CreateInstance(typeof(FooEventArgs),
BindingFlags.NonPublic | BindingFlags.Instance, null,
new object[] { "test string" }, null, null);
// Print the value of bar to the console.
Console.WriteLine(ea.Bar);
// Could also be done via reflection:
string value = (string)ea.GetType().GetProperty("Bar",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ea, null);
Console.WriteLine(value);
}
}public class FooEventArgs : EventArgs
{
// Private constructor that takes one argument.
private FooEventArgs(string bar)
{
_bar = bar;
}private string _bar;
public string Bar
{
get { return _bar; }
set { _bar = value; }
}
}
-
You could use InternalsVisibleToAttribute, to allow your unit tests access.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.