mardi 7 juillet 2015

Arquillian with Mockito and CDI

Is it possible to create spy(mock) object in testing class?

Here is tested class.

@Stateless
@Slf4j
public class UserDao {

    @Inject
    private TestBean testBean;

    public String mock() {
    return testBean.mock();
}

public String notMock() {
    return testBean.notMock();
}
}

TestBean code

@Stateless
@Slf4j
public class TestBean {


    public String notMock() {
        return "NOT MOCK";
    }

    public String mock() {
        return "IMPLEMENTED MOCK";
    }
}

Here's my test

@RunWith(Arquillian.class)
public class UserDataTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Inject
    private UserDao userDao;

    @Deployment
    protected static Archive createWar() {

        File[] dependencies = Maven.configureResolver()
                .withRemoteRepo("nexus-remote", "http://ift.tt/1vx8vSd", "default")
                .withRemoteRepo("nexus-release", "http://ift.tt/1xBQaGP", "default")
                .resolve(
                        "org.slf4j:slf4j-simple:1.7.7",
                        "eu.bitwalker:UserAgentUtils:1.15",
                        "org.mockito:mockito-all:1.10.8"
                ).withoutTransitivity().asFile();

        return ShrinkWrap
                .create(WebArchive.class, "pass.jpa.war")
                .addAsWebInfResource("jbossas-ds.xml")
                .addAsWebInfResource("jboss-deployment-structure.xml")
                .addAsLibraries(
                        PassApiDeployments.createDefaultDeployment(),
                        PassUtilLibrary.createDefaultDeployment(),
                        PassJpaDeployments.createDefaultDeployment()
                ).addAsLibraries(dependencies);
    }

    @Test
public void testMock() {
    assertEquals("MOCK", userDao.mock());
}

@Test
public void testNotMock() {
    assertEquals("NOT MOCK", userDao.notMock());
}
}

I'd like to create a spy object on TestBean to change result on method test() of this bean.

So is it possible to create TestBean spy in UserDao.

I solve some problems through producer like this.

@Singleton
public class MockFactory {

    @Produces
    @ArquillianAlternative
    public TestBean getTestBean() {
        return when(mock(TestBean.class).mock()).thenReturn("MOCK").getMock();
    }
}

But in this example I need create on Bean completely on my own. And if it is bean with additional dependencies and thus i will manage all dependencies.

Aucun commentaire:

Enregistrer un commentaire