1
votes

I would like to write test for a controller class. The controller class takes a service object as constructor parameter. Added the @Inject annotation to the constructor of the service class.

class AssociateService @Inject()(configuration: Configuation){...}

The constructor parameter of the service class is a custom configuration object also created for the application. I added the @Inject to the constructor of the config class as well. Now I'm getting these types of error messages:

No implementation for "className" was bound.

Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.

The configuration class has several constructor parameters, those are "basic" types (Int, Boolean) and one parameter is a custom class type (className). How should I do this binding or is it just enough to annotate something else? And why it says that constructor error message?

1

1 Answers

1
votes

As far as I know, there are two ways with tests and guice, with trade offs:

  1. Don't using field injections, using only constructor injections and fields assignment in constructor for injected parameters. This approach enables very simple solution for testing, just don't use dependency injection in tests. But all your classes must have ability to be created with new operator in test cases...

Ps. You can define optional constructor and use field injections, of course, but it is not very clear solution.

  1. Creating correct module with injectable interfaces binding to its implementations for every test or group of similar tests. Sometimes this approach takes a lot of unnecessary working hours.

You must design your software to maintain testability. Sometimes not every line of code in project need to be tested, sometimes not every code is testable, you must separate it from important parts of your software, that requires testing. If you design your software with single responsibility principe so writing tests is much easer...