Не удалось активировать транзакцию для теста junit - PullRequest
0 голосов
/ 29 апреля 2020

Я хочу проверить транзакционный метод. Я добавил метод @transactional over test, но получил исключение IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional test. Я не знаю, как активировать транзакцию. Я попытался добавить TestTransaction.start() в первую строку тела теста, но выдает исключение, что транзакция не активна. Я не знаю, что случилось с моим тестом. Если я удаляю классы в @SpringbootTest, тест случайным образом выбрасывает NoSuchBeanException для моих репозиториев. Мой метод тестирования:

@ExtendWith(SpringExtension.class)
@DataJpaTest
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
class PersistenceHelperTest {

    @Autowired
    private ReturnRepository returnRepository;
    @SpyBean
    private PersistenceHelper persistenceHelper;


 @Test
void removeFromDbOnWriteExceptionForNotWritableFile(@TempDir Path tempDir) {
    Path testFile = tempDir.resolve("testFile.txt");


     try {
            String content = "This is a test";
            testFile.toFile().createNewFile();
            boolean writable = testFile.toFile().setWritable(false);

            assertTrue("File should not be writable", writable);
            persistenceHelper.saveToFileAndDB(content.getBytes(), testFile.toFile().getAbsolutePath(), returnFile, returnRepository);
            fail();
        } catch (Exception e) {
           assertTrue("Should be instance of IOException", e instanceof IOException);
           assertTrue("Should exists", Files.exists(testFile));
           assertSame(0, returnRepository.findAll().size());
        }
}

Тестируемый класс:

@ Component publi c class PersistenceHelper {

@Transactional(rollbackFor = {IOException.class}, propagation = Propagation.REQUIRES_NEW)
public <T extends BaseEntity> void saveToFileAndDB(byte[] fileContent, String fileAbsolutePath, T entity, JpaRepository<T, Long> jpaRepository) throws IOException {

    FileTransactionListener transactionListener = new FileTransactionListener(new FileDeleter(), fileAbsolutePath);
    TransactionSynchronizationManager.registerSynchronization(transactionListener);
     jpaRepository.save(entity);
        FileUtil.writeToFile(fileAbsolutePath, fileContent);
    }
}

мой класс Springboot:

  @SpringBootApplication
    @EnableTransactionManagement
    @EnableJpaRepositories("packageAddress")
    public class MyApplication {
...