Search

Dark theme | Light theme

March 9, 2009

Access Spring application context in JUnit 4 tests

Just read the Spring Annotations RefCardz and noticed the neat way to access the Spring application context in a JUnit 4 via autowiring. I read the Spring documentation and learned to extend the AbstractJUnit4SpringContextTests, but this is even easier.

The following two classes will do the same thing, but in the second example we don't have to extend a JUnit class.

package com.mrhaki.spring.test;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

// ApplicationContext will be loaded from "classpath:/com/mrhaki/spring/test/ContextTest-context.xml"
@ContextConfiguration
public class ContextJUnitTest extends AbstractJUnit4SpringContextTests {
    @Test
    public void testContext() {
        Assert.assertNotNull(applicationContext.getBean("test"));
    }
}
package com.mrhaki.spring.test;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "classpath:/com/mrhaki/spring/test/ContextTest-context.xml"
@ContextConfiguration
public class ContextTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testContext() {
        Assert.assertNotNull(applicationContext.getBean("test"));
    }
}