Forked from tanapoln/TransactionalAnnotationTest.java
Last active
April 4, 2020 15:53
-
-
Save bakamitai456/a6a4f14df11ca8934b6a1fdf66d91e2b to your computer and use it in GitHub Desktop.
Transactional Unit Testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.wongnai.linter; | |
import java.util.Arrays; | |
import org.junit.Test; | |
import org.springframework.transaction.annotation.Transactional; | |
import com.tngtech.archunit.base.DescribedPredicate; | |
import com.tngtech.archunit.core.domain.JavaClass; | |
import com.tngtech.archunit.core.domain.JavaClasses; | |
import com.tngtech.archunit.core.domain.JavaMethod; | |
import com.tngtech.archunit.core.importer.ClassFileImporter; | |
public class TransactionalAnnotationTest { | |
@Test | |
public void testTransactionalWithCheckedExceptionMustSetRollbackFor() { | |
JavaClasses importedClasses = new ClassFileImporter().importPackages("com.wongnai"); | |
importedClasses.stream() | |
.flatMap(importedClass -> importedClass.getMethods().stream()) | |
.filter(method -> method.isAnnotatedWith(Transactional.class)) | |
.filter(this::isThrowCheckedException) | |
.forEach(this::assertHasRollBackFor); | |
} | |
private void assertHasRollBackFor(JavaMethod checkedExceptionMethod) { | |
Transactional tx = checkedExceptionMethod.getAnnotationOfType(Transactional.class); | |
if (!Arrays.asList(tx.rollbackFor()).contains(Exception.class)) { | |
String name = String.format("%s.%s", checkedExceptionMethod.getOwner().getName(), checkedExceptionMethod.getName()); | |
throw new RuntimeException("Method must contains rollback for: " + name); | |
} | |
} | |
private boolean isThrowCheckedException(JavaMethod method) { | |
return method.getThrowsClause().containsType(DescribedPredicate | |
.describe("checked exception", JavaClass.Predicates.assignableTo(Exception.class))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment