2

我目前正在使用 Glassfish 3.1.2.2 进行我的第一个 EJB 项目。我有两个豆子:

@Singleton
@Startup
public class ABean implements AInterface {
//implementation
}

@DependsOn("ABean")
@Startup
@Singleton
@EJB(name = "ABean", beaninterface = AInterface)
public class BBean implements BInterface {
//implementation
}

我想对“BBean”进行单元测试并模拟“ABean”。目前,当我启动 JUnitTest 时,“ABean”将启动,但有没有办法将“ABean”与“ABeanMock”交换?

我需要一种自动机制来与模拟交换实现,因为这些测试将在詹金斯服务器上运行。因此,手动采用代码对于单个手动测试是可以的,但不能用于自动测试。

我正在使用 Glassfish Embedded API 进行单元测试。

感谢帮助。

4

1 回答 1

0

You can use Arquillian for this.

Arquillian runs your tests inside a container, deploying to an application server if necessary. You can choose to use selected classes only, so this would allow you to create a replacement ABean that implements AInterface, and choose not to deploy the real ABean - which would result in your replacement being used instead.

The test would look something like this:

@Singleton(name = "ABean")
class AMockBean implements AInterface {
  // Mocked bean implementation
}

@RunsWith(Arquillian.class)
public class MyTests {

  @Inject
  private BBean bbean;

  @Deployment
  public Archive<?> deployment() {
     return ShrinkWrap.create(JavaArchive.class)
            .addClass(BBean.class)
            .addClass(AMockBean.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
  }

  @Test
  public void testBBean() {
    bbean.whatever();
  }
}

This is all untested, but it should be something along the lines of this. Depending on your environment and dependencies, it might be more difficult to configure correctly.

Arquillian is a wonderful tool, but it can be difficult to set up exactly the way you want it when starting out. Luckily there are several guides to help you through the process.

于 2012-10-16T11:08:54.720 回答