Java 在集成测试之间刷新共享缓存
我正在使用嵌入式Glassfish 3.1.2执行集成测试。我在测试中做的第一件事是重置数据库,以便每个测试都有一个全新的数据库可以使用 但是,问题是对象被持久化在共享缓存中,而不是存储在数据库中。因此,当下一个测试开始时,它将从缓存而不是数据库中获取旧记录 我可以很容易地通过定义来解决这个问题Java 在集成测试之间刷新共享缓存,java,jpa,glassfish,eclipselink,Java,Jpa,Glassfish,Eclipselink,我正在使用嵌入式Glassfish 3.1.2执行集成测试。我在测试中做的第一件事是重置数据库,以便每个测试都有一个全新的数据库可以使用 但是,问题是对象被持久化在共享缓存中,而不是存储在数据库中。因此,当下一个测试开始时,它将从缓存而不是数据库中获取旧记录 我可以很容易地通过定义来解决这个问题 <property name="eclipselink.cache.shared.default" value="false"/> 但是,我不想禁用persistence.xml文件中的缓
<property name="eclipselink.cache.shared.default" value="false"/>
但是,我不想禁用persistence.xml文件中的缓存,因为稍后会导致性能损失。我只想在测试的时候做。注意,我在这里使用的是JTA数据源
有什么想法吗
脱离主题,我正在尝试学习JavaEE,并遵循GalleriaEE项目,尝试根据我的需要修改它
致以最诚挚的问候退房
因为JPA2.0和EclipseLink原生api都允许清除共享缓存。您可以在测试开始或结束时调用此api
@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;
}
//..
}