是否可以在测试类中创建spy(mock)对象?
这是经过测试的课程。
@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,那么我将管理所有依赖项。
最佳答案
据我所知,不可能将模拟框架与Arquillian结合使用...