samedi 29 août 2015

Guice, DI, and Unit Tests in Play 2.4

So I've been trying to figure this out on my own via documentation but I'm not getting anywhere.

I've got some simple DI bindings setup in a service class that creates a repository object. Simple. However, when I run this in test mode, @Inject does nothing and the repository object is never instantiated.

@Inject
TagRepository tagRepository;

So on the line where it's use, in test mode, we of course get a NullPointerException

tagRepository.tagExistsByName(tag);

This bubbles up into my test like so:

[error] Test services.TagsServiceTest.testAddNewTag failed: java.lang.NullPointerException: null, took 0.097 sec
[error]     at services.TagService.tagExists(TagService.java:27)
[error]     at services.TagService.addNewTag(TagService.java:18)
[error]     at services.TagsServiceTest.testAddNewTag(TagsServiceTest.java:29)

My question is, how do I configure my application to use Guice injectors in test mode? I didn't have this problem with my controllers because requests were actually being made to them, setting up the full application.

One thing I should mention is that I'm using a provider to provide my app to the tests. Should I be using the Guice application builder? If so, where does that go? The play docs aren't very helpful in that regard. Here is the provider

@Override
protected FakeApplication provideFakeApplication() {
    return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), ImmutableMap.of("play.http.router", "router.Routes"), new ArrayList<String>(), null);
}

Aucun commentaire:

Enregistrer un commentaire