Junit 5测试,得到java.lang.IllegalStateException:测试类不能包含@Bean方法

时间:2017-11-26 16:01:30

标签: java spring spring-bean junit5

@ContextConfiguration(classes = ConfigureCustomConfigurationModelProviderTest.class)
    public class ConfigureCustomConfigurationModelProviderTest extends AbstractContextTest {
        @Bean(name = "smth")
        public static ConfigurationModelProvider get() {
            return AnnotationConfigurationModelProvider.getInstance();
        }
        /*...*/
    }

我从junit4迁移到junit5后出现此错误。为什么呢?

1 个答案:

答案 0 :(得分:2)

您应该将每个bean移至@Configuration类,例如TestConfig

@Configuration
public class TestConfig {

    @Bean(name = "smth")
    public static ConfigurationModelProvider get() {
        return AnnotationConfigurationModelProvider.getInstance();
    }
}

并通过@Import

导入
@Import({TestConfig.class})
@ContextConfiguration(classes = ConfigureCustomConfigurationModelProviderTest.class)
public class ConfigureCustomConfigurationModelProviderTest extends AbstractContextTest {
}