Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
1. Generation_P Consulting Ltd
Software Solutions for the Travel Industry
TDD
Make your life better
Antanina Shafranskaya
Antanina.Shafranskaya@generation_p.com
2. TDD: way to better life
Test before code!
TDD principals:
think first
trivial first
test <=> what ; implementation <=> how
different levels of tests
red – green – refactor
red: behavior (responsibility oriented design)
green: coding
refactor: design, refactor
3. TDD: Pair programming
ping – pong
who has keyboard is a King!
through-test driving
10. TDD: Whole test system
manual
auto gui
acceptance
integration
unit tests
11. TDD: Unit tests
One test – one behavior
Independent: isolated class
Reliable
Fast
12. TDD: Integration and Acceptance Tests
integration: component
communication with some
isolation
acceptance: full system test, no
isolation or mocks
client requirements
13. TDD: Mocks
fake – some little implementation
stub – return some predefined result
mock – object with programmed expectation
spy – stub with flow verification
14. TDD: Mockito
Easy to:
stub methods
verify behavior
verify sequence of calls
Cannot:
mock final classes,
methods
mock static
15. TDD: Mockito
@RunWith(MockitoJUnitRunner.class) annotation at
the class-level of the test case
@Mock annotation at mocking objects
init tested class in method annotated with @Before
when(mock.methodCall()).thenReturn(someResult);
doThrow(exception).when(object).voidMethodCall();
verify(mock, times).methodCall()
verifyZeroInteractions(mocks)
inOrder(mock)
17. TDD: PowerMock
Easy way to mock:
static methods
final methods or classes
private methods
construction of new objects
partial mocking
18. TDD: PowerMock
@RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
@PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level
of the test case.
PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of
this class.
PowerMock.mockStaticPartial(ClassThatContainsStaticMethod.class, "methodName",
ArgumentClass.class);
PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to
replay mode.
PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify
mode.
example: http://code.google.com/p/powermock/source/browse/trunk/modules/module-
test/easymock/junit4-
test/src/test/java/samples/junit4/singleton/MockStaticTest.java
19. What to read?
Robert C. Martin “Clean Code: A Handbook
of Agile Software Craftsmanship”
Joshua Kerievsky “Refactoring to Patterns”
Steve Freeman, Nat Pryce “Growing Object-
Oriented Software, Guided by Tests”