How to test JavaFX (MVC) Controller Logic?

天大地大妈咪最大 提交于 2019-12-05 21:53:17

You can use a test framework like Mockito to inject your dependencies in the controller. Thereby you can forgo probably most of the setters, at least the ones that are only present to facilitate testing.

Going with the example code you provided I adjusted the class under test (define an inner class for the FileSorter):

public class LoadController implements Initializable {

    private FileSorter fileSorter = new FileSorter();

    @FXML
    private VBox mainVBox;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //
    }

    public void testOnly(){
        if(mainVBox==null){
            System.out.println("NULL VBOX");
        }else{
            System.out.println("NON-NULL VBOX");
        }
    }

    public static class FileSorter {}
}

The @FXML annotation does not make any sense here, as no fxml file is attached, but it does not seem to have any effect on the code or Test.

Your test class could then look something like this:

@RunWith(MockitoJUnitRunner.class)
public class LoadControllerTest {

    @Mock
    private LoadController.FileSorter fileSorter;
    @Mock
    private VBox mainVBox;
    @InjectMocks
    private LoadController loadController;

    @Test
    public void testTestOnly(){
        loadController.testOnly();
    }
}

This test runs through successfully with the following output:

NON-NULL VBOX

The @Rule JavaFXThreadingRule can be ommited, as when testin like this you are not running through any part of code that should be executed in the JavaFX Thread.

The @Mock annotation together with the MockitoJUnitRunner creates a mock instance that is then injected into the instance annotated with @InjectMocks.

An excellent tutorial can be found here. There are also other frameworks for mocking in tests like EasyMock and PowerMock, but Mockito is the one I use and am most familiar with.

I used Java 8 (1.8.0_121) together with Mockito 1.10.19.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!