Reputation: 1232
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?
Upvotes: 0
Views: 35
Reputation: 63991
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.
Upvotes: 2