I'm calling Component.getInstance(Needed.class)
in the constructor of one of my classes, which is not a seam component.
That works just fine, but I'm trying to cover it with unit tests and what I'm getting is IllegalStateException
on the above line.
Is there a way to cover Component.getInstance with tests?
By the way I'm using unitils library... Thanks in advance
You are using the Service Locator pattern in your classes, which is not suited well for unit testing. Try moving to the Dependency Injection pattern. This makes unit testing much easer.
Service Locator example:
public class MyService : Service
{
private Needed dependency;
public MyService()
{
this.dependency =
Component.getInstance(Needed.class);
}
}
Dependency injection example:
public class MyService : Service
{
private Needed dependency;
public MyService(Needed dependency)
{
this.dependency = dependency;
}
}
When doing dependency injection, your class won't have any reference to the container (Component
in your case), which makes it much easier to unit test the class.