您可以使用自动装配。注意,大多数时候,您对应用程序上下文本身不感兴趣,而对与之关联的一个或多个bean感兴趣。以下是两个实质上执行相同操作的示例:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = HelloWorldConfiguration.class)public class TestApp { @Autowired HelloWorld helloWorld; @Test public void testBean() { helloWorld.setMessage(...); // asserts, etc. }}@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = HelloWorldConfiguration.class)public class TestApp { @Autowired ApplicationContext applicationContext; HelloWorld helloWorld; @Before public void setUp() { helloWorld = context.getBean(HelloWorld.class); } @Test public void testBean() { helloWorld.setMessage(...); // asserts, etc. }}有关详细信息,请参见参考文档。



