I am unit-testing private methods in C# using NUnit.
For example, my method (if public) is expected to throw an ArgumentNullException
. I can assert that the method throws an ArgumentNullException
like so: Assert.Throws<ArgumentNullException>(() => method.Call());
However, since I am invoking a private method using reflection, I would assert a TargetInvocationException
for the method that throws an ArgumentNullException
like so: Assert.Throws<TargetInvocationException>(() => methodInfo.Invoke(obj, new object[] { params }));
I would like to assert an ArgumentNullException
instead of a TargetInvocationException
for that private method so I can scan over its code and know what its expected to do rather than to debug to find out.
How would I assert for the actual exception, instead of a TargetInvocationException
?
NOTE: This question is not addressing the theory behind unit-testing public vs. private methods. My team and I have made the decision to unit-test the private methods, and whether or not that is the way to unit-test is irrelevant to this question. See the most upvoted answer on this question to understand our rationale.