Question

I want to mock an instance of a class that loads a bean in its constructor during its unit-tests. The problem is that Spring is not active during the tests.

My code is:

public class foo{ //the tested class
ObjectA oa;

public foo(){
    oa = SpringService.EnumInstance.LoadOa(); //uses spring to load oa
    }
}

public ObjectA{ //that is an enum 
    ENUM_INSTANCE;

    void func1(){...}
    int func2(){...}
}

public SpringService{
    EnumInstance;

    ObjectA LoadObjectA(){
    ...
    }
} 

If I could, I would change the line

oa = SpringService.EnumInstance.LoadOa(); 

with

oa = new ObjectA(); 

How can I bypass that?

Was it helpful?

Solution

You could do the following :

public class foo{
ObjectA oa;

    public foo(){
       oa = SpringService.EnumInstance.LoadOa(); //uses spring to load oa
    }

    //package private constructor only used in unit test
    foo(ObjectA oa) {
        this.oa = oa;
    }
}

Some people would not be to happy with this solution because you're altering a test subject for testing only purposes, but when serious refactoring is out of the question there is not much else you can do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top