New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Support for reusable mocks #845

Open
ankit-agrawal11 opened this Issue May 17, 2018 · 1 comment

Comments

Projects
None yet
2 participants
@ankit-agrawal11

ankit-agrawal11 commented May 17, 2018

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.

@leonard84

This comment has been minimized.

Member

leonard84 commented Jun 28, 2018

The issue with this request is, that the actual mock interactions are part of the Specification not the mock. Furthermore, the mock syntax only works in Specifications, since it is done via AST magic. So this won't be easy.

However, you can do use a custom org.spockframework.mock.IDefaultResponse to emulate this, albeit with a more low level API. See http://spockframework.org/spock/docs/1.1/all_in_one.html#ALaCarteMocks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment