我正在使用嵌入式 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 项目并尝试根据我的需要对其进行修改。
此致