benxgao
benxgao

Reputation: 371

Do I need focus on testing "public" methods or "private" methods in JUnit test?

are most of the JUnit test written for public methods or private methods? Which do I need to focus on if I have not so much time?

Upvotes: 3

Views: 272

Answers (4)

Jayan
Jayan

Reputation: 18459

You test the behavior of classes. Start with public method. If you cover all states of the object most likely you would cover the private methods. Aim for 100% state coverage ( just a mark. not really achievable in practical cases)

Upvotes: 1

Davek804
Davek804

Reputation: 2804

I doubt you are going to see a whole lot of private methods floating around, that being said, they will show up in a method where the variables involved should not be modified externally/outside of very specific circumstances. That being said, the main difference between public and private is accessibility: private can only be accessed within the class, whereas public can be accessed outside of the class.

Upvotes: 0

Synesso
Synesso

Reputation: 38978

You should to test everything that forms part of the API. Unless you're using reflection, this means the public/protected and package level methods.

Clearly, this is opinion. But it is one based on experience. Let me take my opinion further.

Ideally, you should practice test-driven development. In this practice you:

  1. Write the tests first, including in them the public methods of the test subject that you wish to have. This helps you devise a useful API.
  2. Then you write just enough code to make the tests pass. This will leave you with 100% coverage and no extraneous code.
  3. Then you refactor.

Until you get to the refactoring stage, you probably won't even have any private methods.

Upvotes: 4

dbrin
dbrin

Reputation: 15673

Depends on your goal of testing. Ideally you want to test all of them at 100% coverage :)

Upvotes: 0

Related Questions