It's usually desirable to always take a screenshot when test failed. The concept of JUnit rules makes this an easy task. First, implement a rule as shown below:
Then in your test classes, you just need to declare this rule, then all test methods in it will automatically take screenshot on failure.
The examples here are just for illustration purpose. In real world application, you might make some improvement like:
- Make sure the file name is legal for the OS (for example, the following characters are not allowed in Windows file name: \/:?*<>|\
- Pictures might be further organized into folders by test cases?
- The rule might be declared in a base class so that all test cases have the same behavior without extra boiler plate code