JUnit - before method

26,119

Solution 1

I would 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 benefits of this approach is that it encapsulates a lot of metadata in the base class, sparing you from having to duplicate it in all of your actual test classes.

Solution 2

As you are running your JUnit class with the SpringJUnit4ClassRunner, you can use the 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
    ...
}
Share:
26,119
vlcik
Author by

vlcik

Updated on April 26, 2020

Comments

  • vlcik
    vlcik about 4 years

    I need to execute some piece of code before every JUnit test method. To execute this piece of code I use SpringTest class AbstractTestExecutionListener and its child TransactionContextTestExecutionListener.

    This is 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:

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

    Problem is that beforeTestMethod method is only called before first executed test method. It is not called before all of the rest ones.

    Is problem in configuration? Any idea?

    Thanks

    • btiernay
      btiernay over 11 years
      Just curious if you've tried the standard JUnit @Before annotation?
  • Sudoss
    Sudoss almost 5 years
    Also, If you are manually annotating a method with @BeforeClass or @AfterClass then make those methods static.