Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

Test doubles and EasyMock

251 visualizaciones

Publicado el

About test doubles and the easymock library

Publicado en: Software
  • Inicia sesión para ver los comentarios

  • Sé el primero en recomendar esto

Test doubles and EasyMock

  1. 1. Tests Doubles & EasyMockCreated by Rafael Gutiérrez / / May 2016, JVMMX @ Nearsoft
  2. 2. EasyMock EasyMock is the rst dynamic Mock Object generator, relieving users of hand-writing Mock Objects, or generating code for them.
  3. 3. Mock? What is a Mock? Are you mocking me?
  4. 4. Mock
  5. 5. Wikipedia In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways.
  6. 6. Googling: Mocks Aren't Stubs - Martin Fowler "However to fully understand the way people use mocks it is important to understand mocks and other kinds of test doubles."
  7. 7. What is a Test Double!? Mocks and now Test Doubles!, really?!
  8. 8. Test Doubles They are also known as: Imposters. SUT is a System under test. DOC is a Depended-on Component. Tests Doubles are like Stunt Doubles in lming industry. The movie is the SUT and the leading actor is the real DOC.
  9. 9. Why do you need a test double? Basically, to isolate the code you want to test from its surroundings
  10. 10. Speed up test execution A test double’s implementation is often faster to execute than the real thing. A complex algorithm could take minutes to run, and minutes is FOREVER when we as developers want immediate feedback by running automated tests. You have to test those slow algorithms somewhere but not everywhere.
  11. 11. Make execution deterministic When your code (and tests) is deterministic, you can run your tests repeatedly againts the same code and you will always get the same result. What happen when your code has nondeterministic behaviour: random behaviour, time-depending behaviour? Test doubles can lend a hand with these kinds of sources for nondeterministic behavior.
  12. 12. Simulating special conditions There is always some conditions we can’t create using just the APIs and features of our production code. This happens when our code depends on a third party API, internet connection, an speci c le in some location, etc, etc.
  13. 13. Exposing hidden information What information? information about the interactions between the code under test and its collaborators. Encapsulation and information hiding is a good thing in your code but complicates testing. You could (please don't!) add methods for testing purposes to your production code. By substituting a test double for the real implementation, you can add code for-testing-only and avoid littering your production code.
  14. 14. Types of Test Doubles
  15. 15. Wait, before it is important to understand
  16. 16. Test Stub (I) Also known as: Stub With a Test Stub we can verify logic independently when the SUT depends on indirect inputs from other software components. We use a Test Stub when we need to control the indirect inputs of the SUT.
  17. 17. Test Stub (II) There some variations: A Responder is used to inject valid indirect inputs into the SUT. A Saboteur is used to inject invalid indirect inputs into the SUT. Other variations: Temporary Test Stub, Procedural Test Stub & Entity Chain Snipping
  18. 18. Test Spy (I) Also know as: Spy or Recording Test Stub With a Test Spy we can verify logic independently when the SUT has indirect outputs to other software components. We use a Test Spy as an observation point to capture the indirect outputs for later veri cation.
  19. 19. Test Spy (II) There some variations: Retrieval Interface is a Test Spy with an interface speci cally designed to expose the recorded information. Self Shunt collapses the Test Spy and the Testcase Class into a single object. When SUT calls DOC it is actually calling methods in the Testcase Object. Other variations: Inner Test Double & Indirect Output Registry
  20. 20. Mock Object (I) With a Mock Object we can implement Behaviour Veri cation on the SUT. We con gure the Mock Object with the expected method calls and values with it should respond. When exercising the SUT the Mock Object compares the actual with the expected arguments and method calls and fails if they do not match. No need for assertions in the test method!
  21. 21. Mock Object (II) Mocks could be strict or nice. Strict Mocks if the calls are received in a different order than the expected. Nice Mocks tolerates out-of-order calls. Tests written using Mock Objects look different because all the expected behavior must be speci ed before the SUT is exercised.
  22. 22. Fake Object (I) Also know as: Dummy We use a Fake Object to replace the component the SUT depends with a much lighter-weight implementation. The Fake Object only needs to provide the equivalent services the real DOC provides.
  23. 23. Fake Object (II) There some variations: Fake Databases replace the persistent layer with a Fake Object that is functionally equivalent. When replacing the database with in-memory HashTables or Lists. In-Memory Database is a Dummy database with a small- footprint functionality. Other variations: Fake Web Service & Fake Service Layer
  24. 24. EasyMock by Example
  25. 25. Create a Mock Object 1. Create Mock Object static <T> T EasyMock.mock(Class<T> toMock) 2. Record the expected behaviour 3. Switch the Mock Object to replay state Example: UserServiceImplFindByIdTest
  26. 26. Strick Mocks When using EasyMock.mock()the order of method calls is not checked. Use EasyMock.strictMock()to create a Mock Object that check the order of method calls. Example: UserServiceImplActivateTest
  27. 27. Nice Mocks Mock Objects created with EasyMock.mock()will throw AssertionErrorfor all unexpected calls. A Nice Mocks allows all method calls and returns appropriate empty values (0, null, false) for unexpected method calls. Example: PaymentServiceImplChargeTest
  28. 28. Expectations In Record state the Mock Object does not behave like Mock Object, but it records method calls. Only after calling replay(), it behaves like Mock Object checking whether the expected method class are really done. This means that in record state is where we specify what we expect from the Mock Object.
  29. 29. Behavior of method calls Use: To return a IExpectationSetterswhich we can use to setting expectations for an associated expected invocation. static <T> IExpectationSetters<T> expect(T value) static <T> IExpectationSetters<T> expectLastCall()
  30. 30. IExpectationSettersto answer, return or throw something IExpectationSetters<T> andAnswer(IAnswer<? extends T> answer) IExpectationSetters<T> andReturn(T value) IExpectationSetters<T> andThrow(Throwable throwable) Example: IExpectationSettersToAnswerReturnOrThrowTest
  31. 31. IExpectationSettersto stub responses We stub to respond to some method calls, but we are not interested in how often they are called, when they are called, or even if they are called at all. IExpectationSetters<T> andStubAnswer(IAnswer<? extends T> answer) IExpectationSetters<T> andStubReturn(T value) IExpectationSetters<T> andStubThrow(Throwable throwable) Example: IExpectationSettersToStubTest
  32. 32. IExpectationSettersto specify the number of calls and verify() In EasyMock: IExpectationSetters<T> times(int count) IExpectationSetters<T> times(int min, int max) IExpectationSetters<T> once() IExpectationSetters<T> atLeastOnce() IExpectationSetters<T> anyTimes() static void verify(Object... mocks) Example: IExpectationSettersNumCallsTest
  33. 33. Expectations with Argument Matchers Object arguments are compared using equals()when matching method calls in Mock Objects. This could lead to some issues or maybe we could need a more exible way to match method calls. EasyMockclass contains a lot of prede ned argument matchers for us to use! Example: EasyMockArgumentMatchersTest
  34. 34. Capturing Arguments You can capture the arguments passed to Mock Objects. In EasyMock static <T> T capture(Capture<T> captured) static x captureX(Capture<X> captured) // for primitives Matches any value and captures it in the Captureparameter for later access. You can also specify a CaptureTypetelling that a given Capture should keep the rst, the last, all or no captured values. Example: CapturingArgumentsTest
  35. 35. Mocks concrete Objects? Yes!
  36. 36. Thanks!