Fix primary beans with ApplicationContextAssert
Update `ApplicationContextAssert.getBean` so that multiple beans are supported as long as one of them is primary. This aligns better with the way that the standard `ApplicationContext.getBean` method works. Closes gh-14874
This commit is contained in:
@@ -22,6 +22,10 @@ import org.junit.Test;
|
||||
|
||||
import org.springframework.boot.test.context.assertj.ApplicationContextAssert.Scope;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -244,6 +248,14 @@ public class ApplicationContextAssertTests {
|
||||
.withMessageContaining("but found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanOfTypeWhenHasPrimaryBeanShouldReturnPrimary() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
PrimaryFooConfig.class);
|
||||
assertThat(getAssert(context)).getBean(Foo.class).isInstanceOf(Bar.class);
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanOfTypeWhenFailedToStartShouldFail() {
|
||||
assertThatExceptionOfType(AssertionError.class)
|
||||
@@ -423,4 +435,24 @@ public class ApplicationContextAssertTests {
|
||||
|
||||
}
|
||||
|
||||
private static class Bar extends Foo {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class PrimaryFooConfig {
|
||||
|
||||
@Bean
|
||||
public Foo foo() {
|
||||
return new Foo();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public Bar bar() {
|
||||
return new Bar();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user