spockframework / spockframework/spock

[Feature Request] Support for reusable mocks

Open
#845 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

new feature
Dominant language
Java
Stars
3.6k
Forks
483
PR merge metrics
No merged PRs in 30d

Description

Issue description

I use Spock for testing my Grails applications. Currently, the DetachedMockFactory helps you to create mocks outside Specification, but stubbing is not supported with this feature.

Class FooServiceMocks {
    
    FooService getMockedObject() {
        FooService foo = new DetachedMockFactory().Mock(FooService, name: 'fooService')
        foo.someMethod(_) >> { return 'bar' } // Throws NullPointerException on >> operator
        
        return foo
    }
}

My goal is to define reusable mocks which can be used across multiple test files and override this at places if needed.

Creating a reusable mock is something which is available in many testing libraries. For example, Jest(JavaScript test runner by Facebook) provides a way to define mocks and stub out functions while creating the components.

Quoted from the document:

Manual mocks are defined by writing a module in a mocks/ subdirectory immediately adjacent to the module. For example, to mock a module called user in the models directory, create a file called user.js and put it in the models/mocks directory.

This feature helps the developer to create reusable mocks and inject it across multiple test cases and override them if needed. Here is a sample app which demonstrates the use of this feature.

Is there a way to implement something similar with Spock? The feature would really help with organized code, readability, and maintainability.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing DetachedMockFactory and the existing mock and stubbing behavior described in the issue. Define how reusable mocks should be created, injected, and overridden, then verify that stubbing works outside a Specification and across multiple test files.

Written by the indexing model from the issue text.

Assessment

Tech stack
groovy, java
Domain
testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.