520 likes | 662 Views
Mock Objects in Action. Paulo Caroli & Sudhindra Rao Agile 2009. About us. About us. Paulo Caroli & Sudhindra Rao. About us. Hands-on developers. About us. Open Source. About us. ThoughtWorks. About us. TDD enthusiasts. Agenda. Agenda. History Design for Testability
E N D
Mock Objects in Action Paulo Caroli & Sudhindra Rao Agile 2009 © ThoughtWorks 2008
About us Paulo Caroli & Sudhindra Rao
About us Hands-on developers
About us Open Source
About us ThoughtWorks
About us TDD enthusiasts
Agenda • History • Design for Testability • Dependent Components • Mock Objects in Action • Top Offenders • Q&A
Once upon a time we started writing Unit Tests…
Then we started using unit tests frameworks…
And soon after we started creating (and re-creating) data and implementations to help drive our tests…
Then we came across Mock Objects frameworks…
But frameworks don’t work by themselves!
publicclass Greeting { private Translator translator; privatefinalString HELLO = "Hello"; public Greeting(){ this.translator =new TranslatorImpl(); } public String sayHello(String language, String name){ String message = HELLO; // no need to call translator if the language is English if (!language.equals("English")){ message = translator.translate("English", language, HELLO ); } return message + " " + name; } }
publicclass Greeting { private Translator translator; privatefinalString HELLO = "Hello"; public Greeting(Translator translator){ this.translator = translator; } public String sayHello(String language, String name){ String message = HELLO; // no need to call translator if the language is English if (!language.equals("English")){ message = translator.translate("English", language, HELLO ); } return message + " " + name; } } © ThoughtWorks 2008
Mock Objects Mock Objects enable your unit test to mimic behavior and verify expectations on dependent components.
import static org.mockito.Mockito.*; publicclass GreetingTest{ @Test publicvoid shouldGreetInSomeLanguage(){ // setup Translator translator = mock(Translator.class); Greeting greeting = new Greeting(translator); when(translator.translate("English", "French”,"Hello")). thenReturn("Bonjour"); // execute assertEquals("Bonjour Madame", greeting.sayHello("French", "Madame")); // verify verify(translator).translate("English", "French", "Hello"); } }
Mock Objects Mock Objects enable your unit test to mimic behavior and verify expectations on dependent components.
Mock Objects Mock Objects enable your unit test to mimic behavior and verify expectations on dependent components.
Dependent Components Component A Component B © ThoughtWorks 2008
Remote Component
Database Component
Circular Dependency
Complex Set-up
Exceptional Behavior
Time Dependent Behavior
My co-worker's component
Mock Objects in Action
Mock Objects in Action
Mock Objects Top Offenders
Replacement for integration test
Abuse of mocks (instead: FakeDB, Dummy data, Stub, Test Fixture)