TDD using Mocks & Stubs
Origin
- 1999 in the Londoner TDD/XP/Agile community
- Used to avoid "getters" for more pure OO design
- Back then hardly accepted, because of missing reflection support for Java at that time
- Later implemented by Nat Pryce in Ruby for his PhD
- Used to verify messages sent between objects
- Ported to Java 1.3 using new Proxy objects
- Dynmaock/jMock
Test doubles
(as listed by Martin Fowler)
- Dummy
- Fake
- Stubs
- Spies
- Mocks
https://blog.pragmatists.com/test-doubles-fakes-mocks-and-stubs-1a7491dfa3da
Mockito
- Single dependency
- org.mockito:mockito-core:2.16.0
- Uses Byte Buddy and Objenesis for mocking/stubbing of non-interface classes
- Spies for interaction verification on existing objects
- Different from Martin Fowler's Spy definition!
Mocking with Mockito
import static org.mockito.Mockito.*;
// mock creation
List mockedList = mock(List.class);
// using mock object - it does not throw any "unexpected interaction" exception
mockedList.add("one");
mockedList.clear();
// selective, explicit, highly readable verification
verify(mockedList).add("one");
verify(mockedList).clear();
Stubbing with Mockito
// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing appears before the actual execution
when(mockedList.get(0)).thenReturn("first");
// the following prints "first"
System.out.println(mockedList.get(0));
// the following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
TDD styles
- classical TDD (Detroit school)
- Use real objects if possible
- Use doubles if the real thing is awkward to use (i.e. mail service)
- mockist TDD (London school)
- Use mocks for every object with real behaviour
stubs-mocks
By Kevin Wittek
stubs-mocks
- 1,483