在集成测试之间刷新共享缓存

时间:2013-07-10 08:34:54

标签: java jpa glassfish eclipselink

我正在使用嵌入式Glassfish 3.1.2执行集成测试。我在测试中做的第一件事就是重置数据库,这样每个测试都有一个完全新鲜的数据库可供使用。

然而,问题是对象持久存储在共享缓存中而不存储在数据库中。因此,当下一个测试开始时,它将从缓存而不是数据库中获取旧记录。

我可以通过定义

轻松摆脱这个问题
<property name="eclipselink.cache.shared.default" value="false"/>

在我的persistence.xml文件中。

@BeforeClass
public static void startup() throws Exception { 
                container = EJBContainer.createEJBContainer();
                context = container.getContext();
    }

@Before
public void setUp() throws Exception {
  //Clean database before every test using dbunit
}

@Test // This is the first test, works well since the test is first in order
public final void testCreateUser() throws Exception {       
    UserService userService = (UserService) context.lookup("java:global/galleria/galleria-ejb/UserService");
    User user = new User(TEST_USER_ID, TEST_PASSWORD);
    User actualUser = userService.signupUser(user);
    assertTrue(actualUser != null);
    assertEquals(TEST_USER_ID, actualUser.getUserId());
    assertFalse(Arrays.equals(TEST_PASSWORD, actualUser.getPassword()));
    logger.info("Finished executing test method {}", testMethod.getMethodName());
}



 @Test // This is the second test, fails since the database not is clean
 public final void testCreateUser() throws Exception {      
    UserService userService = (UserService) context.lookup("java:global/galleria/galleria-ejb/UserService");
    User user = new User(TEST_USER_ID, TEST_PASSWORD);
    User actualUser = userService.signupUser(user); // FAILS since TEST_USER_ID already in cache!!

    //..
 }

@Stateless
@EJB(name = "java:global/galleria/galleria-ejb/UserService", beanInterface = UserService.class)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class UserServiceImpl implements UserService
{
    @EJB
    private UserRepository userRepository;

    @Override
    @PermitAll
    public User signupUser(User user) throws UserException {            

        User existingUser = userRepository.findById(user.getUserId());
        if (existingUser != null)
        {
            logger.error("Attempted to create a duplicate user.");
            throw new UserException(DUPLICATE_USER);
        }

        try {
             user = userRepository.create(user);
        } catch (EntityExistsException entityExistsEx) {
            logger.error("Attempted to create a duplicate user.");
            throw new UserException(DUPLICATE_USER, entityExistsEx);
        }
        return user;
    }

        //..
}

但是,我不想在persistence.xml文件中禁用缓存,因为稍后我会失去性能。我只想在测试时这样做。请注意,我在这里使用JTA数据源。

有什么想法吗?

关闭主题,我正在尝试学习java ee,并遵循Galleria EE项目并尝试根据我的需要对其进行修改。

祝你好运

1 个答案:

答案 0 :(得分:1)

结帐http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching 因为JPA 2.0和EclipseLink native api都允许清除共享缓存。您可以在测试的开始或结束时调用此API。