Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to TDD a JFrame?

Tags:

java

tdd

jframe

I'm working on a new project, where I want to display some data on the screen. I set myself to using TDD which is new for me, but I love the idea and get along quite OK so far.

I set up a JFrame, add a Textarea and put text there, but how can I properly test this? Or is this wrong thinking in the TDD context on my side? I want to be sure (in the TDD way), that the data gets displayed correctly! The creation of the text that gets displayed is properly covered with tests, but the displaying is not.

Here is a completely simplified example:

public class MyTextDisplay {
    public static void main(String[] args) {
        JFrame my_frame = new JFrame("DisplaySomeText");
        my_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextArea textArea = new JTextArea(5, 20);
        textArea.setEditable(false);

        my_frame.add(textArea);
        my_frame.setVisible(true);

        //this would be in a separate method
        textArea.append("Hello World");
    }
}
like image 582
Bastian Doeen Avatar asked May 18 '12 06:05

Bastian Doeen


1 Answers

TDD requires you to think about things a little bit differently. You first determine what you are going to test, and how you are going to test it before you actually write any code for the solution.

For GUI's, this can become quite tricky, and, in all honesty, your GUI should never contain any logic that could be in a separate layer. For example, the value that is displayed should come from an object that has nothing to do with the GUI, but that can be tested individually. That allows you to develop the main business logic (model and controller) separate from the display (view). This is the MVC pattern. Test Driven Development simply means that you test what you can before you write code, and, as you add more code, more tests will start to pass.

I'd rather focus on my design and ensure that whatever is generating the text value works as expected. The GUI should be "dumb" and only focus on displaying or retrieving values, with little, if any concern for if the displayed values are indeed correct.

As a GUI is notoriously difficult to test with automated tools (properly test), I'd avoid that as much as possible and decouple my GUI from my actual application as much as I can. Then you can test the GUI once, to make sure it displays what it's supposed to, and focus on the business logic without having to do continuous tests on the GUI as you are not touching that code.

like image 167
Ewald Avatar answered Sep 27 '22 18:09

Ewald