Spring 单元测试 之 JUnit 4
If you are using JUnit 4 to create tests with the TestContext framework, you will have two options to
access the managed application context. The first option is by implementing the
ApplicationContextAware interface. For this option, you have to explicitly specify a Spring-specific test
runner for running your test—SpringJUnit4ClassRunner. You can specify this in the @RunWith annotation
at the class level.
如果你使用Junit4与TestContext框架做测试,那么有2种选项来访问被管理的Application Context. 第一种就是实现ApplicationContextAware接口,使用这种方式必须要明确指定Spring的Test Runner来运行测试 - SpringJUnit4ClassRunner. 你可以使用类级别的@RunWith注释来指定它
第一种方法
import static org.junit.Assert.*;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "/beans.xml")public class AccountServiceJUnit4ContextTests implements ApplicationContextAware {private static final String TEST_ACCOUNT_NO = "1234";private ApplicationContext applicationContext;private AccountService accountService;public void setApplicationContext(ApplicationContext applicationContext) {this.applicationContext = applicationContext;}@Beforepublic void init() {accountService =(AccountService) applicationContext.getBean("accountService");accountService.createAccount(TEST_ACCOUNT_NO);accountService.deposit(TEST_ACCOUNT_NO, 100);}@Testpublic void deposit() {accountService.deposit(TEST_ACCOUNT_NO, 50);assertEquals(accountService.getBalance(TEST_ACCOUNT_NO), 150, 0);}@Testpublic void withDraw() {accountService.withdraw(TEST_ACCOUNT_NO, 50);assertEquals(accountService.getBalance(TEST_ACCOUNT_NO), 50, 0);}@Afterpublic void cleanup() {accountService.removeAccount(TEST_ACCOUNT_NO);}}import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@ContextConfiguration(locations = "/beans.xml")public class AccountServiceJUnit4ContextTests extendsAbstractJUnit4SpringContextTests {private static final String TEST_ACCOUNT_NO = "1234";private AccountService accountService;@Beforepublic void init() {accountService =(AccountService) applicationContext.getBean("accountService");accountService.createAccount(TEST_ACCOUNT_NO);accountService.deposit(TEST_ACCOUNT_NO, 100);}...}