of tests • Key concepts • Rules - things to remember • A developer’s toolset • Live coding - hmm… unit testing actually @ppapapetrou76 / @skj_jug Thessaloniki Java Meetup - Unit Testing #skg_unittesting
It doesn’t matter how well written it is; it doesn’t matter how pretty or object-oriented or well-encapsulated it is. With tests, we can change the behavior of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse.” — Michael Feathers Working Effectively With Legacy Code (2004) @ppapapetrou76 / @skj_jug #skg_unittesting Thessaloniki Java Meetup - Unit Testing
Approaching development from a unit testing perspective is that you'll likely be writing code that is easy to test • Prevent future changes from breaking functionality ( safety pillow ) @ppapapetrou76 / @skj_jug #skg_unittesting Thessaloniki Java Meetup - Unit Testing
Meetup - Unit Testing • Assertion -> A way to validate expected output / behavior of a method • Examples ◦ Assert.assertEquals (a, b) ◦ Assert.assertTrue ( bool ) • Each unit test should include only one assertion
Meetup - Unit Testing • Setup and teardown methods are not abused. It’s better to use factory methods for readability • Each test tests one thing only • Check for good and consistent naming conventions • Make sure that only meaningful assert messages are used, or none at all (meaningful test names are better)
Meetup - Unit Testing • Asserts are separated from actions (different lines). • Tests don’t use magic strings and values as inputs. use the simplest inputs possible to prove your point. • There is consistency in location of tests. make it easy to find related tests for a method, or a class, or a project.
Meetup - Unit Testing • Unit tests are isolated from each other and repeatable • Testing private or protected methods is not the norm (public is always better) • Tests are not over-specified • State-based testing is preferred over using interaction testing
Meetup - Unit Testing • Strict mocks are used as little as possible (leads to over specification and fragile tests) • There is no more than one mock per test • Tests do not mix mocks and regular asserts in the same test (testing multiple things)
Meetup - Unit Testing • Unit Tests ‘verify’ mock calls only on the single mock object in the test, and not on all the fake objects in the tests • Unit Tests verify only on a single call to a mock object. Verifying multiple calls on a mock object is either over specification or testing multiple things.
Meetup - Unit Testing • Tests does not contain logic or dynamic values • Check coverage by playing with values (booleans or constants) • Unit tests are separated from integration tests • Unit tests don’t use things that keep changing in a unit test (like DateTime.Now ). Use fixed values.
Meetup - Unit Testing • Unit tests don’t assert with expected values that are created dynamically - you might be repeating production code. • Unit tests should not do exception handling.