Monday, May 5, 2014

[add-on] mock cdi-beans with deltaspike

i've prototyped an add-on for apache deltaspike which allows to mock cdi-beans manually or with a mocking-framework.

an example for a simple cdi-bean:
@RequestScoped
public class MyCdiBean
{
private int count = 0;
public int getCount()
{
return count;
}
public void increaseCount()
{
count++;
}
}
view raw MyCdiBean.java hosted with ❤ by GitHub
an example for a simple manual-mock for the cdi-bean:
@RunWith(CdiTestRunner.class)
public class ManuallyMockedCdiBeanTest
{
@Inject
private MyCdiBean myCdiBean;
@Inject
private DynamicMockContext mockContext;
@Test
public void manualMock()
{
mockContext.addMock(new MyCdiBean() {
@Override
public int getCount() {
return 14;
}
});
Assert.assertEquals(14, myCdiBean.getCount());
myCdiBean.increaseCount(); //no effect due to the mock
Assert.assertEquals(14, myCdiBean.getCount());
}
}
an example for a simple mockito-mock for the cdi-bean:
@RunWith(CdiTestRunner.class)
public class MockitoMockedCdiBeanTest
{
@Inject
private MyCdiBean myCdiBean;
@Inject
private DynamicMockContext mockContext;
@Test
public void mockitoMock()
{
MyCdiBean mockedCdiBean = mock(MyCdiBean.class);
when(mockedCdiBean.getCount()).thenReturn(14);
mockContext.addMock(mockedCdiBean);
Assert.assertEquals(14, this.myCdiBean.getCount());
myCdiBean.increaseCount(); //no effect due to the mock
Assert.assertEquals(14, this.myCdiBean.getCount());
}
}
the same is possible in combination with qualifiers as well as with producers and @Typed beans.

the add-on is available here. the repository also contains several tests, which illustrate the supported use-cases. the tests use manual-mocks as well as mockito-mocks. however, you can provide any object as mock which is a subclass of the original implementation.