samedi 29 août 2020

Using a Stub in global setup in Spock

I am trying to prepare some abstract setup for a tested object and I am stuck when it comes to using a Stub there. Basically what I am trying to achieve - I have a Facade being created like this:

Facade facade(EventBus eventBus)

I have different test classes for different use cases - in most of the tests I don't need to interact with the eventBus, so I would like it to be a simple implementation like

event -> just("No event bus configured")

But I would also like to have a possibility to check if proper events were published there so I would like also to be able to inject a Stub if needed. Another aspect of it is that I need some code in setupSpec method to properly set up the facade before the tests and I would like to avoid doing it in setup method.

How I would see it:

abstract class AbstractSpec extends Specification {

@Shared
Facade facade = new Facade(
        eventBus())

def setupSpec() {
    runDifferentMethodsOnTheFacade()
}

EventBus eventBus() {
    return { event -> just("No event bus configured") }
}

Whereas in the class where I would like to verify EventBus calls I would have something like this:

class DerivedSpec extends AbstractSpec {

EventBus eventBus = Mock()

def "check if proper event was emited"() {
    given:
        ExpectedEvent publishedEvent

    when:
        def someId = facade.doSomething().block()

    then:
        1 * eventBus.push(_ as ExpectedEvent) >> { ExpectedEvent event -> publishedEvent = event }
        publishedEvent.id() == someId
}

EventBus eventBus() {
    return eventBus
}
}

Is it somehow achievable? Are the Spock extensions helpful in such case? I guess the simplest solution would be to resign from extending the AbstractSpec in this particular test and just reuse the setupSpec code in setup for this single class but I am curious if there is another way to solve it.

Aucun commentaire:

Enregistrer un commentaire