How to inject a mock for a field (using autowired) in a Grails service that is under unit test?

669 views Asked by At

In my current setup i want to unit test a Grails service that has an @autowired dependency and inject a mock for the dependency.

class AcmeService {

    @Autowired
    FooService fooService // not a Grails service!
}

The FooService is not a Grails service but it is a dynamic implementation from a FeignClient. I am looking for a way to inject a Mock for the FooService service in a UnitTest. What would be the best solution to do this?

I tried setting the dependency in the setup, but then i get a 'Unsatisfied dependency expressed through field fooService'

class AcmeService extends Specification {

    FooService mockedFooService = Mock(FooService)

    def setup() {
        service.fooService = mockedFooService
    }
}
1

There are 1 answers

0
Graeme Rocher On BEST ANSWER

you can add the following to your unit test:

def doWithSpring = {
    fooService( InstanceFactoryBean, Mock(FooService) )
}