如何创建或模拟用于编写Junit测试用例的ejb 3 SessionContext

时间:2012-01-30 14:27:47

标签: junit

我正在尝试测试我的ejb会话bean

myFacadeBean = new MyFacadeBean();
MyEntity myEntity = myFacadeBean .getMyData("Hello");

我试图在我的会话bean中测试一个方法。我使用

创建了EntityManager
 entityManager = Persistence.createEntityManagerFactory("Test").createEntityManager();

我正在测试这些ejb的外部容器。所以我按如下方式配置了我的persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="Test" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>test.entity.MyEntity</class>

        <properties>
            <property name="eclipselink.target-database" value="Oracle" />
            <property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver" />
            <property name="eclipselink.jdbc.url"
                value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
            <property name="eclipselink.jdbc.user" value="user" />
            <property name="eclipselink.jdbc.password" value="pass" />
        </properties>
    </persistence-unit>
</persistence>

我如何在此scneario中创建SessionContext,因为myFacadeBean正在使用sessionContext来访问callerPrincipal()。getName();

我不想使用像Ejb3unit

这样的东西

1 个答案:

答案 0 :(得分:0)

TestFun-JEE允许您模拟SessionContext,以便您可以决定callerPrincipal()。getName()返回的内容。

@Local
public interface UserEjb {
    String getCurrentUser();
}

@Stateless
public class UserEjbImpl implements UserEjb{

    @Resource
    private SessionContext sessionContext;

    @Override
    public String getCurrentUser() {
        return sessionContext.getCallerPrincipal().getName();
    }
}

@RunWith(EjbWithMockitoRunner.class)
public class MockSessionContextTest {

    @Mock
    private SessionContext sessionContext;

    @EJB
    private UserEjb userEjb;

    @Test
    public void testSessionContextMock() {
        when(sessionContext.getCallerPrincipal()).thenReturn(new Principal() {
            @Override
            public String getName() {
                return "kuki";
            }
        });

        assertEquals("kuki", userEjb.getCurrentUser());
    }

}