Before you read this post please read: Use
a CDI alternative as a mock implementation for a stateless session bean
So, since you are familiar with the above post, now let's suppose that
we have multiple mock implementations. In such cases, the problem is how to
instruct the container to choose between the implementations? The answer relies
on alternatives priority!
Basically, we annotate each mock implementation with @Priority and
provide a number as the level of priority. The higher number has the higher
priority. Here it is three mock implementations with priorities 1,2 and 3:
@Priority(1)
@Alternative
@Stateless
public class
FooServiceMock implements IFooService {
@Override
public List getAllFoo() {
return Arrays.asList("foo 1",
"foo 2", "foo 3");
}
}
@Priority(2)
@Alternative
@Stateless
public class
BestFooServiceMock implements IFooService {
@Override
public List getAllFoo() {
return Arrays.asList("best foo 1",
"best foo 2", "best foo 3");
}
}
@Priority(3)
@Alternative
@Stateless
public class
GreatFooServiceMock implements IFooService {
@Override
public List getAllFoo() {
return Arrays.asList("great foo 1",
"great foo 2", "great foo 3");
}
}
The mock implementation annotated with @Priority(3)
has the higher priority. When we run the below code CDI will automatically
choose the GreatFooServiceMock:
@Named
@RequestScoped
public class
FooBean {
private static final Logger LOG =
Logger.getLogger(FooBean.class.getName());
@Inject
private IFooService fooService; // choose GreatFooServiceMock
public void loadAllFoo() {
List allfoo = fooService.getAllFoo();
LOG.log(Level.INFO, "allfoo:{0}",
allfoo);
}
}
Now, we can also write a test using CDI-Unit as below (this will also
choose the GreatFooServiceMock):
@RunWith(CdiRunner.class)
@ActivatedAlternatives({FooServiceMock.class,
BestFooServiceMock.class, GreatFooServiceMock.class})
public class
FooBeanTest {
@Inject
FooBean fooBean;
@Test
@InRequestScope
public void testStart() {
fooBean.loadAllFoo();
}
}
We can use the @Priority annotation to specify alternatives globally for an application that consists of multiple modules like this:
@Alternative
@Priority(Interceptor.Priority.APPLICATION+10)
public class ...
The complete example is available here.
Niciun comentariu :
Trimiteți un comentariu