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.
Found my answer:
UPDATE
Assert.IsNotNull(exception.InnerException)lets me know that an inner exception exists.Assert.IsInstanceOf<Exception>(exception.InnerException);will assert any type ofExceptionthrown. I agree that both ways tell us that there is an inner exception.However…..what if I want to assert for a specific type of inner exception?
For example, if my method throws an
ArgumentNullException, then I cannot assert for that by doingAssert.IsInstanceOf<FileNotFoundException>(exception.InnerException);UsingAssert.IsNotNulllets me know that an inner exception exists, but it does not reveal the type of the inner exception. Therefore, this is why I prefer usingIsInstanceOfin this case.