Tutorials
Swing TestingLike the wasCancelled()method, the name() method is not thread-safe, so our test class needs another boilerplate helper method:
Using this, we can write our nameTest():
The main points of this test are as follows.
Note 1: Here we simply check that with no value entered into the text fi eld, the method returns null. This could have gone into the constructor test.
Note 2: UISaveAsDialog has an enterName() method that types in the name and then presses Enter. In this test we want to type in a name, but not yet activate Ok by pressing Enter. So we use the Cyborg in the UISaveDialog to just type the name, and then we check the value of name(). This part of the test helps to define the method SaveAsDialog.name() by establishing that a value is returned even when the Ok button has not been activated.
Note 3: Here we are just testing that activating the Ok button has no effect on the value of name(). Later, we will also test whether the Ok button disposes the dialog.
It would be tempting to write some reflective method that made methods like name(), wasCancelled(), and enteredName() one-liners. However, that would make these examples much harder to understand. A bigger problem, though, is that we would lose compile-time checking: reflection breaks at runtime when we rename methods.
Our tests have used the show() method because it is used in init(). So we can be sure that show() actually does bring up the SaveAsDialog user interface. What we will check in showTest()is that the show() method blocks the calling thread.
In the first sub-test, we check that cancellation of the SaveAsDialog wakes the launching thread. In the second sub-test, we check that activation of the Ok button wakes the launching thread.