Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use VisibleForTesting for pure JUnit tests

I´m running pure JUnit4 java tests over my pure java files on my project but I can't find a way to use @VisibleForTesting clearly without making the thing manually public.

Ex:

@VisibleForTesting public Address getAddress() {   return mAddress; } 

The method has to be public to let it be "public" to tests, but in that case the annotation doesn't make sense right? why not just use a comment if the annotation will not do nothing?

like image 640
Daniel Gomez Rico Avatar asked Oct 21 '15 19:10

Daniel Gomez Rico


People also ask

What does Visiblefortesting annotation do?

Denotes that the class, method or field has its visibility relaxed, so that it is more widely visible than otherwise necessary to make code testable.

Which of the given annotation can be used to mark test as unit test?

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class. To define that a certain method is a test method, annotate it with the @Test annotation. This method executes the code under test.


2 Answers

Make the method package-private and the test will be able to see it, if the test is in the corresponding test package (same package name as the production code).

@VisibleForTesting Address getAddress() {   return mAddress; } 

Also consider refactoring your code so you don't need to explicitly test a private method, try testing the behaviour of a public interface. Code that is hard to test can be an indication that improvements can be made to production code.

The point of an annotation is that its convention and could be used in static code analysis, whereas a comment could not.

like image 175
MikeJ Avatar answered Oct 02 '22 09:10

MikeJ


According to the Android docs:

You can optionally specify what the visibility should have been if not for testing; this allows tools to catch unintended access from within production code.

Example:

@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) public Address getAddress() 
like image 20
Rodrigo Borba Avatar answered Oct 02 '22 07:10

Rodrigo Borba