Arquillian与Mockito和CDI

时间:2015-07-07 11:47:52

标签: testing mockito cdi jboss-arquillian

是否可以在测试类中创建间谍(模拟)对象?

这是经过测试的课程。

@Stateless
@Slf4j
public class UserDao {

    @Inject
    private TestBean testBean;

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

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

TestBean代码

@Stateless
@Slf4j
public class TestBean {
    public String notMock() {
        return "NOT MOCK";
    }

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

这是我的考试

@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://maven.wideup.net/nexus/content/groups/public/", "default")
                .withRemoteRepo("nexus-release", "http://maven.wideup.net/nexus/content/repositories/releases/", "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());
    }
}

我想在TestBean上创建一个间谍对象来改变这个bean的方法test()的结果。

因此可以在UserDao中创建TestBean间谍。

我通过像这样的制作人解决了一些问题。

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

但是在这个例子中我需要完全依靠在Bean上创建。如果它是具有额外依赖性的bean,那么我将管理所有依赖项。

2 个答案:

答案 0 :(得分:0)

据我所知,不可能将模拟框架与arquillian结合使用......

答案 1 :(得分:0)

我自己没有使用它,但这个Arquillian扩展似乎专门用于支持Arquillian测试中的Mockito Spy对象:https://github.com/topikachu/arquillian-extension-mockito/