How To Test Exception Handling When Setting The System Look And Feel
By Adrian Sutton
Setting the system look and feel is a common task in applications and if you’re shooting for 100% test coverage, it’s problematic because it uses two static methods and has checked exceptions. Typically you have something like:
void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// Handle exception somehow.
}
}
As far as I know, there’s no way to write a test that doesn’t also exercise UIManager, so we’ll have to live with that, but we can test that the UI is set and the exception handled.
public void testSetNativeLookAndFeel() {
_editor.setNativeLookAndFeel();
assertEquals(UIManager.getSystemLookAndFeelClassName(), UIManager.getLookAndFeel().getClass().getName());
}
public void testErrorWhileSettingNativeLookAndFeel() {
System.setProperty("swing.systemlaf", "foobar");
_editor.setNativeLookAndFeel(); // Check the exception was handled correctly.
}
There’s going to be very little value in the test because the usual error handling will be to just log the exception and keep going, but if you prefer to keep tests at 100% coverage to avoid the slippery slope, it will cover the code and ensure it does what you want.