1

I read a little about TDD and testing in general and decided I wanna give it all a try.

After finding out how to run tests in Android Studio, I realized most of my methods are private (thus making it wrong to test them directly, as per this link: How do I test a class that has private methods, fields or inner classes? ).

What gives? Is this a design smell? Should I refactor somehow?

Given that I should only be able to write code after a failing test, how would I go about classes that have very few public methods, such as most of my activities? Did I miss something?

Please have in mind that I'm new to this.

Community
  • 1
  • 1

1 Answers1

5

Most people I talk about this agree that you should only test your API methods. If you assume that the purpose of a class private methods is to support the public methods, then the fact that your public methods are working correctly kind of implies that your private methods are also working correctly.

When I have a private method that is somewhat complex and that I really think should be unit tested, I simply make it package-private (no modifier) so it's not exposed in the class API but can still be accessed by the test class.

Addressing your questions specifically:

What gives? Is this a design smell? Should I refactor somehow?

It doesn't sound like a design smell. On the contrary, having more private methods than public methods probably means that your class code is modular and follows the encapsulation principle.

Given that I should only be able to write code after a failing test, how would I go about classes that have very few public methods, such as most of my activities? Did I miss something?

Assuming you are creating a new class from scratch, I would do something like this:

  1. Design the class API methods
  2. For each API method:
    1. Write the unit tests for the method
    2. Write the code until the tests pass
    3. Refactor the method, extracting private methods as needed

If you do it this way, you can be sure that your private methods are covered, since you tested their functionality through the public method.

Also, a code coverage tool such as JaCoCo or Cobertura may be helpful in finding which parts of your code lack proper testing.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48