Hi Kyriakos,

The most straight-forward way to combine dependency injection and unit testing 
(with mocks) is indeed constructor injection as in the docu page you linked. 
However, this only works if that object is created in a DI-aware way, that is, 
either injected itself or created with something like 
[i]Components#newInstance[/i]. In this case, it's currently created manually 
with [i]new[/i], so injections don't work.

In order to make your class DI-aware and still a singleton, you can annotate it 
with the [url=https://github.com/google/guice/wiki/Scopes]@Singleton[/url] 
scope and make sure it's injected by classes using it instead of grabbed 
through [i]#getInstance[/i]. But be aware that this will only work if classes 
using it are injected (or more precisely: DI-aware) themselves.

public MyRESTService1 {
        // inject this somehow - ideally through constructor
        private final MyClass myClass;


public class MyClass {
        private final SimpleTranslator i18n;

        public MyClass(SimpleTranslator i18n) {
                this.i18n = i18n;

        public doSomething() {

If for some reason injecting [i]MyClass[/i] is not an option, you could work 
around it by manually provding a [i]SimpleTranslator[/i] from unit tests. 
Either use [i]Components#setComponentProvider[/i] with some binding for 
[i]SimpleTranslator[/i] or, more directly, create a protected setter for 
[i]i18n[/i], which is visible within the same package, where your test class 
probably is. But those are somewhat hacky workarounds; proper constructor 
injection is most likely the high road.


Context is everything: 

For list details, see http://www.magnolia-cms.com/community/mailing-lists.html
Alternatively, use our forums: http://forum.magnolia-cms.com/
To unsubscribe, E-mail to: <user-list-unsubscr...@magnolia-cms.com>

Reply via email to