Testing java.util.prefs.Preferences void method with mockito

733 views Asked by At

I don't know how to test correctly void method with Preferences object inside, this is a method which I want to test:

public void setPersonFilePath(File file, ViewGenerator viewGenerator) {
    Preferences prefs = Preferences.userNodeForPackage(ViewGenerator.class);
    if (file != null) {
        prefs.put("filePath", file.getPath());

        // Update the stage title.
        viewGenerator.getPrimaryStage().setTitle("AddressApp - " + file.getName());
    } else {
        prefs.remove("filePath");

        viewGenerator.getPrimaryStage().setTitle("AddressApp");
    }
}

And here is my test class:

private FileManager fileManger;
private File file;
private ViewGenerator viewGenerator;
private Preferences preferences;

@Before
public void prepareDependencies() {
    MockitoAnnotations.initMocks(this);
    fileManger = new FileManager();
    file = mock(File.class);
    viewGenerator = mock(ViewGenerator.class);
}

@Test
public void test() {

    fileManger.setPersonFilePath(file, viewGenerator);
    verify(preferences).remove("filePath");
}

I've tried mocking preferences, as well as initializing preferences with new object inside test method.

1

There are 1 answers

6
JB Nizet On

Mockito can't mock static methods like Preferences.userNodeForPackage().

My advice would be to wrap these static calls into a custom class PreferenceManager, and to inject an instance of PreferenceManager into the object under test.

You could then mock PreferenceManager, inject the mock, and make it return a mock Preferences.