joy
joy

Reputation: 3

Nunit Test - To test a part of private method code that is being called by public method

I'm trying to test a piece of code in a private method(Method A). In the flow this private method is being called by a public method. In order to test this code in method A. It returns data from another private method(method B)

public returntype MyTest()
{
  this.methodA();
}

private returntype methodA()
{
 rep = this.methodB(some paramethers);
// code to be tested using rep
}

private returntype methodB()
{
//some code
}

How do I test this code?

Upvotes: 0

Views: 69

Answers (2)

Charlie
Charlie

Reputation: 13681

Andreasnico's answer is a statement of testing philosophy - one I have often agreed with. But the question is a how-to, so I'm going to answer it that way and then come back to the philosophy part.

Obviously, if your method is private you can't call it (except by reflection, which would be a bit silly, in my view). The easiest thing to do is to make it public and stick a comment in front of it that says "public for testing only!" Your coding standards or views on Object Orientation, might tell you not to do that but bear in mind that some early unit testing frameworks were developed using languages that don't have visibility modifiers and got along just fine without them. For average (non-financial) business apps, I see no harm in doing that.

The second easiest approach is to make the method Internal and to make internals visible to your test assembly. For NUnit's own tests, that's what we are now doing although we have lots of legacy code that uses the first approach.

<philosophy> This isn't a good place for an extended discussion of white-box versus black-box unit testing. NUnit (and other frameworks) was originally created by and for developers who were testing the implementation of their designs. So the tests got right into the dirty details. If you are the developer - as opposed to a tester - there's nothing wrong with doing that kind of testing. In fact, if you want to do TDD in the smallest possible steps, that's what you have to do. It's just important, IMO, that you know which kind you are doing at any moment. A good test suite will usually have both kinds of tests. </philosophy>

Upvotes: 1

andreasnico
andreasnico

Reputation: 1488

Private methods are just implementation details, and hence all functionality should be testet through the public interface. In your case through the "MyTest" method.

Upvotes: 0

Related Questions