如何模拟actionContext

时间:2019-04-05 06:41:38

标签: junit struts

我测试时ActionContext为null,我只想知道如何模拟它或其他解决问题的方法?

我测试的是

ActionContext ctx= ActionContext.getContext(); 
session = ctx.getSession();

//使用会话将值传输到jsp

public class JUnitTestBase extends 
AbstractTransactionalJUnit4SpringContextTests{

public static XmlWebApplicationContext context = null;
//static MockActionProxy request;
public static String[] CONFIG_FILES = { "classpath*: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);
//ApplicationContext context =new ClassPathXmlApplicationContext("file:src/applicationContext-*.xml");
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!");
}
}

public class BloggerServiceTest extends JUnitTestBase{

private IBloggerService bloggerService;

public BloggerServiceTest() {
    bloggerService=(IBloggerService) context.getBean("BloggerService");
}

@Test
public void testLogin() throws Exception{
    IBloggerDAO bloggerDao=createMock(IBloggerDAO.class);
    BloggerBasic bloggerBasic=new BloggerBasic();
    bloggerBasic.setBloggerName("123");
    bloggerBasic.setBloggerPasswd("123");
    expect(bloggerDao.checkNameAndPasswd(anyObject(String.class), anyObject(String.class))).andReturn(new BloggerBasic());
    replay(bloggerDao);  
    assertEquals(true, bloggerService.login(bloggerBasic));  
    verify(bloggerDao); 
}

}

0 个答案:

没有答案