Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should unit test member variables be private or public?

Tags:

java

junit

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?

like image 551
hennes Avatar asked Mar 19 '23 04:03

hennes


1 Answers

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).

like image 142
Mureinik Avatar answered Mar 26 '23 01:03

Mureinik