• Stars
    star
    165
  • Rank 228,906 (Top 5 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swift helpers for mocking and stubbing

Dobby

Dobby provides a few helpers for mocking and stubbing.

Matchers

Matchers can be matched with values, serving as the fundamental building block for mocking and stubbing. There are many functions that help creating matchers for (equatable) types, including optionals, tuples, arrays, and dictionaries with equatable elements:

matches { $0 == value } // matches value
any() // matches anything
not(0) // matches anything but 0
none() // matches Optional<T>.None (nil)
some(1) // matches Optional<T>.Some(1)
equals(1) // matches 1
equals((1, 2)) // matches (1, 2)
equals((1, 2, 3)) // matches (1, 2, 3)
equals((1, 2, 3, 4)) // matches (1, 2, 3, 4)
equals((1, 2, 3, 4, 5)) // matches (1, 2, 3, 4, 5)
equals([1, 2, 3]) // matches [1, 2, 3]
equals([1: 1, 2: 2, 3: 3]) // matches [1: 1, 2: 2, 3: 3]

Matchers may also be nested:

matches((matches { $0 == 0 }, any(), 2)) // matches (0, _, 2)
matches((not(equals(3)), some(any()))) // matches (not(3), _)
matches([any(), equals(4)]) // matches [_, 4]
matches(["key": matches { $0 == 5 }]) // matches ["key": 5]

Mocks

Mocks can be used to verify that all set up expectations have been fulfilled.

Strict mocks

By default, mocks are strict and the order of expectations matters, meaning all interactions must be expected and occur in the order they were expected:

let mock = Mock<[Int]>()
mock.expect(matches([any(), matches { $0 > 0 }])) // expects [_, n > 0]
mock.record([0, 1]) // succeeds
mock.verify() // succeeds
mock.record([1, 0]) // unexpected, fails (fast)

The order of expectations may also be ignored:

let mock = Mock<[Int]>(ordered: false)
mock.expect(matches([0, 1]))
mock.expect(matches([1, 0]))
mock.record([1, 0]) // succeeds
mock.record([0, 1]) // succeeds
mock.verify() // succeeds
mock.record([0, 0]) // unexpected, fails (fast)

Nice mocks

Nice mocks allow unexpected interactions while still respecting the order of expectations:

let mock = Mock<[Int?]>(strict: false)
mock.expect(matches([some(0)]))
mock.expect(matches([some(any())]))
mock.record([nil]) // unexpected, ignored
mock.record([1]) // out of order, ignored
mock.record([0]) // succeeds
mock.verify() // fails
mock.record([1]) // succeeds
mock.verify() // succeeds

Of course, nice mocks can ignore the order of expectations too:

let mock = Mock<[String: Int?]>(strict: false, ordered: false)
mock.expect(matches(["zero": some(0)]))
mock.expect(matches(["none": none()]))
mock.record(["some": 1]) // unexpected, ignored
mock.record(["none": nil]) // succeeds
mock.record(["zero": 0]) // succeeds
mock.verify() // succeeds

Negative expectations

In addition to normal expectations, nice mocks allow negative expectations to be set up:

let mock = Mock<Int>(nice: true)
mock.reject(0)
mock.record(0) // rejected, fails (fast)

Verification with delay

Verification may also be performed with a delay, allowing expectations to be fulfilled asynchronously:

let mock = Mock<Int>()
mock.expect(1)

let mainQueue: DispatchQueue = .main
mainQueue.asyncAfter(deadline: .now() + 1) {
    mock.record(1) // succeeds
}

mock.verify(delay: 2) // succeeds

Stubs

Stubs, when invoked, return a value based on their set up behavior, or, if an interaction is unexpected, throw an error. Behavior is matched in order, i.e., the function or return value associated with the first matcher that matches an interaction is invoked/returned:

let stub = Stub<(Int, Int), Int>()
let behavior = stub.on(equals((2, 3)), return: 4)
stub.on(matches((any(), any()))) { x, y in x * y }
try! stub.invoke((2, 3)) // returns 4
try! stub.invoke((3, 3)) // returns 9

Behavior may also be disposed:

behavior.dispose()
try! stub.invoke((2, 3)) // returns 6

Example

The helpers provided for mocking and stubbing can be used with any testing approach, including protocol test implementations, test subclasses, etc. For example, imagine you want to verify interactions with the following class and change its behavior:

class MyClass {
  func myMethod(fst: String, _ snd: String) -> String {
    return fst + snd
  }
}

Writing a test subclass for the given class is very simple:

class MyClassMock: MyClass {
  let myMethodMock = Mock<(String, String)>()
  let myMethodStub = Stub<(String, String), String>()
  override func myMethod(fst: String, _ snd: String) -> String {
    myMethodMock.record((fst, snd))
    // Throw an exception if the stub doesn't define any behavior for the interaction.
    return try! myMethodStub.invoke((fst, snd))
  }
}

The test subclass allows you to verify that all your set up expectations are fulfilled and enables you to change its behavior on-the-fly:

let myClassMock = MyClassMock()
myClassMock.myMethodMock.expect(matches(("Hello", "World")))
myClassMock.myMethodStub.on(any()) { fst, snd in fst }
myClassMock.myMethod("Hello", "World") // returns "Hello"
myClassMock.myMethodMock.verify() // succeeds

If you ever find yourself wanting to use a mock or stub with several interactions of different types, consider using an equatable enum to define these interactions.

Documentation

Please check out the source and tests for further documentation.

About

Dobby was born at trivago 🏭

More Repositories

1

prettier-plugin-sort-imports

A prettier plugin to sort imports in typescript and javascript files by the provided RegEx order.
TypeScript
3,284
star
2

parallel-webpack

Builds multi-config webpack projects in parallel
JavaScript
1,483
star
3

gollum

An n:m message multiplexer written in Go
Go
939
star
4

Heimdallr.swift

Easy to use OAuth 2 library for iOS, written in Swift.
Swift
639
star
5

cluecumber

Clear and concise reporting for the Cucumber BDD JSON format.
Java
270
star
6

Heimdall.droid

Easy to use OAuth 2 library for Android by trivago.
Kotlin
258
star
7

melody

Melody is a library for building JavaScript web applications.
JavaScript
215
star
8

prettier-plugin-twig-melody

Code formatting plugin for Prettier which can handle Twig/Melody templates
JavaScript
155
star
9

cucable-plugin

Maven plugin that simplifies running Cucumber scenarios in parallel.
Java
115
star
10

triava

The triava project contains several of trivago's core libraries for Java-based projects: caching, collections, annotations, concurrency libraries and more.
Java
75
star
11

scalad

Horizontal Job Autoscaler for Nomad
Go
69
star
12

hamara

Export datasource from the existing Grafana DB into a YAML provisioning file
Go
57
star
13

tgo

trivago go utilities
Go
57
star
14

jade

A simple but yet powerful library to expose your entities through JSON API.
PHP
55
star
15

nomad-pot-driver

Nomad task driver for launching freebsd jails.
Go
54
star
16

Protector

A circuit breaker for InfluxDB
Python
48
star
17

fastutil-concurrent-wrapper

Set of concurrent wrappers around fastutil primitive maps
Java
37
star
18

babel-plugin-cloudinary

Compile cloudinary URLs at build time.
JavaScript
24
star
19

pbf-loader

Webpack loader for .proto files to be used within mapbox/pbf
JavaScript
21
star
20

rumi

trivago continuous integration executor
PHP
20
star
21

influxdbviewer

JavaScript
18
star
22

preact-hooks-testing-library

preact port of https://github.com/testing-library/react-hooks-testing-library
TypeScript
18
star
23

project-ironman

CSS skeleton / structure we used at trivago for our large scale refactoring project called Project Ironman
CSS
17
star
24

logstash-codec-protobuf

Protobuf codec for parsing data into logstash
17
star
25

samsa

A high level NodeJS stream processing library
TypeScript
17
star
26

jcha

Java Class Histogram Analyser
Java
17
star
27

hive-lambda-sting

A small library of hive UDFS using Macros to process and manipulate complex types
Java
15
star
28

reportoire

Kotlin
15
star
29

ReactiveHeimdall

Reactive wrapper around Heimdall.swift
Swift
14
star
30

chapi

chronos & marathon console client - Manage your jobs like a git repository
PHP
14
star
31

rebase

A small python library to make your data layer more robust.
Python
13
star
32

Mail-Pigeon

Mail Pigeon is a mail delivery plattform, which was created in the trivago developer days (something like the Google 20% rule) to replace some of the PHP based mailing scripts that were present that days. trivago has a lot of customers and therefore the focus laid on the fast and relyable sending process of a future mail tool. We decided to build a plattform that just can send mails in a performant manner, later on we built mail pigeon on top of it.
Java
13
star
33

boerewors

Release framework based on Python
Python
11
star
34

rtl-scss-kit

A right-to-left mixin set to create right-to-left and left-to-right css out of one scss-source
CSS
8
star
35

svn-daemon

A daemon to control a svn checkout via a web interface, written in go.
Go
8
star
36

exporter-edgecast

A Prometheus exporter for the Edgecast CDN
Go
7
star
37

triversity

trivago's university collaboration tool
Vue
7
star
38

libvips-mozjpeg-amazonlinux-buildscript

Modified libvips build script which helps to build libvips with mozjpeg support on AWS 'AmazonLinux' EC2 instances.
Shell
7
star
39

junior-java-software-engineer-casestudy

Case study for Junior Software Engineer - Java Backend Services
6
star
40

exporter-chinacache

A Prometheus exporter for the Chinacache CDN
Go
5
star
41

express-booking-selfconnect-api

trivago Express Booking - Self Connect API
PHP
5
star
42

recsys-challenge-2019-benchmarks

Run benchmark algorithms on the data sets of the RecSys Challenge 2019. https://recsys.trivago.cloud/
Python
4
star
43

create-melody-app

Create Melody apps quickly from the command line.
JavaScript
3
star
44

oauth-sdk-js

A tiny javascript library that allows to log in/register with trivago
JavaScript
2
star
45

melody-web

Public web site of the Melody JavaScript framework
HTML
2
star
46

.github

@trivago organization
2
star
47

intellij-idea-plugin

Internal IntelliJ plugin by trivago. Quick and dirty implementation.
Kotlin
1
star
48

melody-template

Melody Starter Example
JavaScript
1
star
49

mod_whatkilledus

Copy of sources from https://emptyhammock.com/projects/httpd/diag/
C
1
star
50

TriMamba

Collection of tools aimed to gather event information from different sources into a database
JavaScript
1
star