package unittest; import org.junit.AfterClass; import org.junit.BeforeClass; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.XmlWebApplicationContext; /** * 测试Service的基类 * * @author http://blog.csdn.net/fansunion/ * */ public class JUnitTestBase { public static XmlWebApplicationContext context = null; public static String[] CONFIG_FILES = { "file:src/applicationContext-*.xml" }; public JUnitTestBase() { System.out.println("JUnitTestBase"); } @BeforeClass public static void setUp() { System.out.println("Test start…"); context = new XmlWebApplicationContext(); context.setConfigLocations(CONFIG_FILES); MockServletContext msc = new MockServletContext(); context.setServletContext(msc); context.refresh(); msc.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); } @AfterClass public static void tearUp() { System.out.println("Test end!"); } } package unittest; import static org.junit.Assert.assertEquals; import org.junit.Test; import action.UserService; public class UserServiceTest extends JUnitTestBase { private UserService userService; public UserServiceTest() { userService = context.getBean(UserService.class); } @Test public void test() { String name = "http://FansUnion.cn"; String myName = userService.getName(name); assertEquals(name, myName); } } |