0

I configured our integration tests to use the database from testcontainer. We are testing the DAO layer so there are cases when another Entity is required to be passed for a DAO method. I recieve the LazyInitialzeException in case the passed input entity contains Lazy loaded collection. How can I configure the testcontaier and spring to use Transactional?

This is the base class that configures the testcontainers:

@Testcontainers
public class PostgreSQLContainerInitializer {

@Container
private static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:14-alpine")
        .withReuse(Boolean.TRUE)
        .withDatabaseName("vdx");

@BeforeAll
static void initContainer() throws IOException, InterruptedException {
    postgres.execInContainer("mkdir", "/tsd01");
    postgres.execInContainer("chown", "-R", "postgres.postgres", "/tsd01/");
    postgres.execInContainer("mkdir", "/tsi01");
    postgres.execInContainer("chown", "-R", "postgres.postgres", "/tsi01/");

    ScriptUtils.runInitScript(new JdbcDatabaseDelegate(postgres, ""), "init-database-test.sql");
}

@DynamicPropertySource
static void registerPgProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
}

}

This is the testing class/method:

@TestPropertySource(locations = {"classpath:config/application-test-containers.properties"})
@DataJpaTest
@Import({AdvertiserDao.class, AdvertiserLogger.class, AdvertiserDataDao.class, CompanyDao.class, CompanyLogger.class, UserDao.class, RoleDao.class,
     CompanyDao.class, UserLogger.class})
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@EnableTransactionManagement
public class AdvertiserDaoTest extends PostgreSQLContainerInitializer {

@Autowired
private CompanyDao companyDao;

@Autowired
private UserDao userDao;

@Autowired
private AdvertiserDao advertiserDao;

@Autowired
private EntityManager entityManager;

@Test
@Transactional
public void testCreate() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    AdvertiserDto advertiserDto = objectMapper.readValue(CompanyDaoTest.class.getResourceAsStream("/test-data/advertiser/advertiser2.json"),
                                                         AdvertiserDto.class);

    Company systemCompany = companyDao.getSystemCompany();
    User systemUser = userDao.getSystemUser();

    Advertiser advertiser = advertiserDao.create(advertiserDto, systemCompany, systemUser);

    assertNotNull(advertiser.getId());
}

}

I receive the LazyInitialize error when the "advertiserDao.create(advertiserDto, systemCompany, systemUser);" is called.

Somebody does know how it can be configured TestContainers and @DataJpaTest to use Transactional?

0 Answers0