Don’t assign static references to instance method calls in Java

Image for post
Image for post
Photo by Luca Bravo on Unsplash
/**
* Foo.java
*/

public class Foo {
public static String foo = Config.getInstance().getFoo();
}
/**
* FooTest.java
*/

import org.junit.Test;

public class FooTest {
@Test
public void TestSetFooA() {
Config.getInstance().setFooConfig("bar");
assert Foo.foo == "bar";
}

@Test
public void TestSetFooB() {
Config.getInstance().setFooConfig("fizz");
assert Foo.foo == "fizz";
}
}
/**
* Foo.java
*/

public class Foo {
public static String foo() {
return Config.getInstance().getFoo();
}
}
/**
* Foo.java
*/

public class Foo {
public static String foo(Config config) {
return config.getFoo();
}
}
/**
* FooTest.java
*/

import org.junit.Test;
import static org.mockito.Mockito.*;

public class FooTest {
@Test
public void TestSetFooA() {
Config mockedConfig = mock(Config.class);
when(mockedConfig.getFoo()).thenReturn("bar");

assert Foo.foo(mockedConfig) == "bar";
}

@Test
public void TestSetFooB() {
Config mockedConfig = mock(Config.class);
when(mockedConfig.getFoo()).thenReturn("fizz");

assert Foo.foo(mockedConfig) == "fizz";
}
}

Patrick is a software engineer from New England. Today, he resides in the Emerald City, waiting patiently for the Kraken to be released.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store