組み込みの 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 プロジェクトに従って、自分のニーズに合わせて変更しようとしています。
よろしくお願いします