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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With