Sample Java Web Archive Project
- YouTube
- Try to make sure all of your behavior is under unit test coverage
- If you find logic without a unit test, you have probably uncovered a part of your system that is unnecessarily difficult to maintain
- Consider the case of web dispatch. It is common to check each possible http path with a test that spins up a web server, but is this an informed design choice or unnecessary complexity stemming from bad assumptions?
- Before beginning, be sure you can actually run the example
- mvn package
- java -jar jetty-runner.jar target/hello-web-1.0.war
- open a web browser
- navigate to
- more about jetty-runner
Following the code
- The intent here is to demonstrate that if you have logic you don't know how to unit test, you should try moving that logic somewhere that is easier to unit test.
- map everything to the same entry point in your web.xml
- When you have multiple entry points, something is deciding which entry point to use.
- This application behavior, so why is it not under unit test coverage?
- By moving this specification of behavior from an xml file to a file in a programming language, we make it easier to test.
- make sure you code entry point never has reason to change: EntryPointServlet
- you only need to unit test anything that could possibly break
- your application logic has change with business needs
- the rules for your application container don't change as often
- use dependency injection assemble app from unit testable parts: DependencyInjection
- create a layer between integration points and logic
- since both HttpServletRequest and HttpServletResponse are both behind a java interface, we can use fakes/stubs/mocks to verify any interaction we like
- alternatively, you can do what I have done here, create value objects that can be used in both production and test code
- now the dispatch is easy to unit test without spinning up a web server
- Types of Tests
- making things easy to unit test is not technically challenging, it is a matter of making design decisions that favor ease of unit testing
- thinking of it as test driven design is helpful in that it emphasises how unit tests make the design of your code better
- checking for correctness is an important, but secondary concern
- if your code is incorrect but you have a good design, it is easy to fix
- if your code is correct but you have a bad design, it becomes increasingly more difficult over time to maintain correctness as the code needs to change
- any time you see conditional logic without a unit test, push that logic away from a container/framework, and towards a programming language, where it is easy to unit test