Skip to content

Instantly share code, notes, and snippets.

@alainsahli
Last active March 25, 2019 08:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alainsahli/a3d8fd26adc527aa422c to your computer and use it in GitHub Desktop.
Save alainsahli/a3d8fd26adc527aa422c to your computer and use it in GitHub Desktop.
spring-test issue when using multiple @ContextConfiguration defined on a base class and on a composed annotation
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(classes = AnotherAppContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class AbstractBaseTest {
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AnotherAppContext {
@Bean
public AnotherBean anotherBean() {
return new AnotherBean("Bar");
}
static class AnotherBean {
private final String value;
AnotherBean(String value) {
this.value = value;
}
public String value() {
return this.value;
}
}
}
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.springframework.test.context.ContextConfiguration;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target(TYPE)
@Retention(RUNTIME)
@ContextConfiguration(classes = TestAppContext.class)
public @interface ComposedAnnotation {
}
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ComposedAnnotation
public class ComposedAnnotationTest extends AbstractBaseTest {
@Autowired
private TestAppContext.MyBean myBean;
/**
* This test fails
*/
@Test
public void myBeanMustNotBeNull() throws Exception {
assertNotNull(this.myBean);
assertEquals("Foo", this.myBean.value());
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestAppContext {
@Bean
public MyBean myBean() {
return new MyBean("Foo");
}
static class MyBean {
private final String value;
MyBean(String value) {
this.value = value;
}
public String value() {
return this.value;
}
}
}
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration(classes = TestAppContext.class)
public class WorkingTest extends AbstractBaseTest {
@Autowired
private TestAppContext.MyBean myBean;
/**
* This test passes
*/
@Test
public void myBeanMustNotBeNull() throws Exception {
assertNotNull(this.myBean);
assertEquals("Foo", this.myBean.value());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment