fili
fili copied to clipboard
Clean up "defaulting" in mocks and other objects in our tests
We have lots of duplication in some places where we're defining basically the same behaviors or data on mocks or other objects, but each tests tweaks it a little bit. We should clean this duplication up using some sort of a "build a default with overrides" pattern.
To make this pattern easier, here's some sample code:
// try 1
def setupMock(Closure overrides = {}) {
// Create the thing to return
def mock = Mock(Thing)
// Call the setup closure, passing it the thing
overrides.call(mock)
// Set up the default behaviors
mock.method() >> "Default"
return mock
}
def "test override"() {
setup:
def myMockThing = setupMock {
// Set up my specific behaviors
it.method() >> "Overridden"
}
expect:
myMockThing.method() == "Overridden"
}
def "test default"() {
setup:
def myMockThing = setupMock()
expect:
myMockThing.method() == "Default"
}
// try 2
def setupMock(Closure defaults = {}, Closure overrides = {}) {
// Create the thing to return
def mock = Mock(Thing)
// Call the setup closure, passing it the thing
overrides.call(mock)
// Set up the default behaviors
defaults.call(mock)
return mock
}
// TODO: How to use? Curry?
def "test override"() {
setup:
def myMockThing = setupMock {
// Set up my specific behaviors
it.method() >> "Overridden"
}
expect:
myMockThing.method() == "Overridden"
}
def "test default"() {
setup:
def myMockThing = setupMock()
expect:
myMockThing.method() == "Default"
}
// try 3
T setupMock(Class<T> type, Closure defaults = {}, Closure overrides = {}) {
// Create the thing to return
T mock = Mock(type)
// Call the setup closure, passing it the thing
overrides.call(mock)
// Set up the default behaviors
defaults.call(mock)
return mock
}
// TODO: How to use?
def "test override"() {
setup:
def myMockThing = setupMock {
// Set up my specific behaviors
it.method() >> "Overridden"
}
expect:
myMockThing.method() == "Overridden"
}
def "test default"() {
setup:
def myMockThing = setupMock()
expect:
myMockThing.method() == "Default"
}
I will keep an eye one this as I develop features and write tests in existing Specs.