如何访问带有@RunWith和@ContextConfiguration注解的jUnit测试中的Spring上下文?

o2rvlv0m  于 2023-08-02  发布在  Spring
关注(0)|答案(5)|浏览(109)

我有下面的测试课

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest {

  @Autowired
  MyService service;
...

}

字符串
是否有可能在其中一种方法中以编程方式访问services-test-config.xml?比如:

ApplicationContext ctx = somehowGetContext();

sbdsn5lh

sbdsn5lh1#

这也很好用:

@Autowired
ApplicationContext context;

字符串

ztmd8pv5

ztmd8pv52#

由于测试也会像Spring bean一样被示例化,所以你只需要实现ApplicationContextAware接口:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

字符串
对于非XML的需求,你也可以这样做:

@RunWith(SpringJUnit4ClassRunner.class)
/* must provide some "root" for the app-context, use unit-test file name to the context is empty */
@ContextConfiguration(classes = MyUnitTestClass.class)
public class MyUnitTestClass implements ApplicationContextAware {

jjhzyzn0

jjhzyzn03#

如果测试类扩展了Spring JUnit类
(e.g.、AbstractTransactionalJUnit4SpringContextTests或任何其他扩展AbstractSpringContextTests的类),您可以通过调用getContext()方法来访问app上下文。
查看org.springframework.test包的javadocs

gtlvzcf8

gtlvzcf84#

可以使用SpringClassRuleSpringMethodRule规则注入ApplicationContext类的示例。如果你想使用另一种非Spring跑步机,这可能是非常方便的。下面是一个例子:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

字符串

m1m5dgzv

m1m5dgzv5#

创建了一个与这个问题相关的帖子,这真的有助于获得信心
Try this link for more details

@Test
void TestBeanLaunch()
{
    context.run(it -> {
        /*
         * I can use assertThat to assert on the context
         * and check if the @Bean configured is present
         * (and unique)
         */
        assertThat(it).hasSingleBean(PracticeApplication.class);
        assertThat(it).hasSingleBean(PracticeApplication.TestBean.class);
        assertThat(it.getBean("BeanTest")).isInstanceOf(PracticeApplication.TestBean.class);
    });
}

字符串

相关问题