Java testing (public, private)

Suppose you are testing a class with the public method A and the private method B, and now B can only be tested indirectly. What is the best way to test B directly?

1) Make B public

2) Make B `public only during testing.

3) Make B protected

4) Make B access by default.

+4
source share
3 answers

A code health check should not determine the access level for your method.

When you create a private method, it is usually used to modulate your code, or possibly other refactoring. Unless it is an API that is open, it is not a candidate for unit testing in any way.

So, the question you should first ask is: β€œDo I need to expose B ()?” If the answer is still no, then the question of testing it becomes irrelevant.

A very useful link for unit testing approaches is Clean Codes .

+3
source

The best way is to make the beta method private and place the SomehtingTest class in the same package as the Something class.

+2
source

The best way would be to make it publicly available, but if that is not possible, you can also use reflection to verify it.

Detailed information can be found here. How to check a class with private methods, fields or inner classes?

0
source

Source: https://habr.com/ru/post/1495159/


All Articles