JUnit - before method

I need to execute a piece of code before each JUnit test method. To execute this piece of code, I use the SpringTest AbstractTestExecutionListener class and its child TransactionContextTestExecutionListener.

This is the code:

public class TransactionContextTestExecutionListener extends AbstractTestExecutionListener{ private static final Logger logger = Logger.getLogger(TransactionContextTestExecutionListener.class); @Override public void beforeTestMethod(TestContext testContext) throws Exception { Object ctx = testContext.getApplicationContext().getBean(Context.class); } 

My JUnit class looks like this:

 @ContextConfiguration(locations = "classpath:/META-INF/spring-test/tests-context.xml") @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners(TransactionContextTestExecutionListener.class) @Transactional public class SelectQueryBuilderTest {} 

The problem is that the beforeTestMethod method is called only before the first execution of the Test Method. He is not called in front of everyone else.

Is there a configuration problem? Any idea?

thanks

+4
source share
2 answers

I suggest trying @Before . For example, consider creating a base class for your test:

 @ContextConfiguration(locations = "classpath:/META-INF/spring-test/tests-context.xml") @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners(TransactionContextTestExecutionListener.class) @Transactional public class BaseQueryBuilderTest { @Autowired private ApplicationContext applicationContext; protected Context context; @Before public void setUp() { context = applicationContext.getBean(Context.class); } } 

And now you can write your test implementation as follows:

 public class SelectQueryBuilderTest extends BaseQueryBuilderTest { @Test public void test() { // Use context } } 

One of the advantages of this approach is that it encapsulates a lot of metadata in the base class, eliminating the need to duplicate it in all of your real test classes.

+6
source

When you run your JUnit class using SpringJUnit4ClassRunner , you can use JUnit 4 annotations:

 @Before public void multipleInit() { // Called before each method annotated with @Test ... } @BeforeClass public static void initAll() { // Called once per class, before any method annotated with @Test is called ... } 
+11
source

Source: https://habr.com/ru/post/1439806/


All Articles