Вот мой упрощенный пример приложения:
Код: Выделить всё
@RestController
public class MyController {
private final MyRepository myRepository;
private final MyService myService;
public MyController(MyRepository myRepository, MyService myService) {
this.myRepository = myRepository;
this.myService = myService;
}
@GetMapping
@Transactional
public String justForTest() {
var myEntity = new MyEntity().setStatus("NEW");
myRepository.save(myEntity);
try {
myService.throwsAnRuntimeException();
// on service succeed
myEntity.setStatus("SUCCESS");
} catch (Exception e) {
// on service fail
myEntity.setStatus("FAIL");
throw e;
} finally {
myRepository.save(myEntity);
}
return "this is the end";
}
}
Код: Выделить всё
@Data
@Entity
@Accessors(chain = true)
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String status;
}
Код: Выделить всё
@Repository
public interface MyRepository extends JpaRepository {
}
Код: Выделить всё
@Service
public class MyService {
public void throwsAnRuntimeException() {
throw new RuntimeException("Rollbacks not working!");
}
}
Но когда я пытаюсь протестировать этот код с помощью @DataJpaTest (база данных h2 в пути к классам для области тестирования):
Код: Выделить всё
@DataJpaTest
class MyControllerTest {
@Autowired
private MyRepository repository;
@Test
void justForTest() {
var controller = new MyController(repository, new MyService());
assertThrows(RuntimeException.class, controller::justForTest);
var afterTestEntities = repository.findAll();
System.out.println(afterTestEntities.getFirst());
assertEquals(0, afterTestEntities.size());
}
}
Итак, мой главный вопрос — как протестировать @Transactional механизм в модульных тестах?
Подробнее здесь: https://stackoverflow.com/questions/791 ... atajpatest
Мобильная версия