Consider the following (pseudo-ish) unit test class.
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MyTest {
private static final int MY_CONSTANT = 7;
private Object object;
@Before
public void setUp() throws Exception {
object = new Object();
}
@Test
public void test1() {
Assert.assertEquals(MY_CONSTANT, object.property1);
}
}
What I'd like to know is whether there is any best practice for which access modifier to use for the members MY_CONSTANT and object. In a non-test class you would obviously expose as little of the class internals as possible and use the private modifier. However, in a unit test that doesn't seem to matter much, so we could also make the members public.
So is it really arbitrary which access modifier I use or am I missing something?
It's a matter of taste and project standards, but I usually go for the rule of thumb that says that if there's no good reason to have it public (or protected, for that matter), it should be private. This prevents other tests from mistakenly using these member variables (again, unless there's a good reason) and mainly helps give the project a streamlined look - production code and testing code follow the same standards.
EDIT:
As mentioned by @dkatzel in the comments (thanks!) some fields annotated by JUnit's (or other similar frameworks) annotations must have a specific set of modifiers. E.g., fields annotated with @Rule must be public and fields annotated with @ClassRule must be public static (at least from JUnit 4.11. Earlier 4.x versions are a bit more lax about the static modifier).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With