Anand Sunderraman
Anand Sunderraman

Reputation: 8128

Groovy / Spock test a Java class that has a member @Inject

I am trying to test a Java class that has a member injected using @Inject.

I want to test the someMethod

public class SomeJavaClass {

    @Inject
    private SomeFactory someFactory;

    private SomeDAO someMethod(Map someMap) {
        SomeDAO someDAO = someFactory.create();
        //some code
    }
}

My class does not have a explicit constructor

Upvotes: 1

Views: 1522

Answers (2)

Marcin Grzejszczak
Marcin Grzejszczak

Reputation: 11149

Of course you can inject to private fields (Guice and Spring can do that). You can use my extension but it would be much better if you added the constructor since then it follows the OOP practices.

Upvotes: 1

Luis Muñiz
Luis Muñiz

Reputation: 4811

If your field is private, and you don't use constructors, how do you inject it? I will assume that this was a mistake, because if you inject something from the outside, you need to provide an interface for it.

So here's a spock spec that does what you ask, but exposes someFactory as a protected member:

import spock.lang.Specification
import spock.lang.Subject

import javax.inject.Inject

interface SomeFactory {
    SomeDAO create()
}

class SomeDAO {

}

class SomeJavaClass {

    @Inject
    protected SomeFactory someFactory;

    protected SomeDAO someMethod(Map someMap) {
        SomeDAO someDAO = someFactory.create();
        //some code
    }
}

class SomeJavaClassSpec extends Specification {

    def someFactory = Mock(SomeFactory)
    @Subject
    SomeJavaClass subject = new SomeJavaClass(
            someFactory: someFactory
    )

    def "It uses a factory to create some object"() {
        when:
        subject.someMethod([:])

        then:
        1 * someFactory.create() >> new SomeDAO()
    }
}

You can also use the spock collaborators extension annotations to inject your collaborator Mocks automatically:

https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension

Upvotes: 1

Related Questions