Test Doubles

Understanding and implementing Test Doubles in software testing

Test doubles are used to create fast, independent, deterministic, and reliable tests. They stand in for real components, similar to how stunt doubles are used in movies.

Test Double

Types of Test Doubles

Resources

Example

@Before
public void init() throws Exception {
    userService = Mockito.spy(userService);
    ObjectMapper mapper = new ObjectMapper();
    spyData = mapper.readValue(new File(TestConstants.DATA_FILE_ROOT + "user_spy.json"), User.class);
    Mockito.doReturn(spyData).when(userService).getUserInfo(TestConstants.userId);
}

@Test
public void verifySpyUserDetails() throws Exception {
    User user = userService.getUserInfo(TestConstants.userId);
    verify(userService).getUserInfo(TestConstants.userId);
    verify(userService, times(1)).getUserInfo(TestConstants.userId);

    Assert.assertEquals(spyData.getManager(), user.getManager());
    Assert.assertEquals(spyData.getVp(), user.getVp());
    Assert.assertEquals(spyData.getOrganization(), user.getOrganization());
    Assert.assertEquals(spyData.getDirector(), user.getDirector());
}

@After
public void cleanUp() {
    reset(userService);
}
  

Platform Independent Mocking Frameworks

Framework Reasoning
JSON-Server Simple, great for scaffolding; Follows REST conventions; Stateful
Mountebank Allows for more than just HTTP (multi-protocol); Simple to use and configure; Large language support

GraphQL

Framework Reasoning
GraphQL-Faker Supports proxying existing GraphQL APIs; Simple GraphQL directive-based data mocking; Uses faker.js under the hood
GraphQL-Tools Built-in utilities for mocking collections (MockList); Great documentation and interoperability with existing GraphQL (NodeJS) solutions

Platform Specific

Javascript

Framework Reasoning
expect(jest) For all generic assertions/mocking
jest-dom For DOM assertions
supertest For in-process test a http server
nock For http server endpoint assertion/mocking with NodeJS

Android

Framework Reasoning
MockK (Kotlin projects) Provides a common when this →then that mocking API in an Idiomatic Kotlin DSL; Built-in support for mocking top-level functions, extensions, static objects; Detailed documentation with examples
MockWebServer Process local mock server; Embedded in tests, no separate mock execution; Simplistic but powerful API that can support state

iOS

Java (BE)

Framework Reasoning
Powermock Superset of Mockito; Provides Static mocking functionality
Mockito Standard mocking tool; Has annotations for easy creation of many mocks at test construction
Last modified September 26, 2024: chore: improve images and seo (dc539dd)