package tests.jfun.yan.web;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import tests.jfun.models.BankAccount;
import jfun.yan.Container;
import jfun.yan.web.YanLoader;
import jfun.yan.web.YanLoaderListener;
import jfun.yan.web.YanLoaderServlet;
import com.mockobjects.servlet.MockServletConfig;
import com.mockobjects.servlet.MockServletContext;
import junit.framework.TestCase;
public class YanLoaderTestCase extends TestCase {
public void testContextLoaderServletWithDefaultContext() throws Exception {
MockServletContext sc = new MyServletContext(".");
sc.setInitParameter(YanLoader.CONFIG_FILE_PARAM,
"tests/jfun/yan/web/yan.xml");
HttpServlet servlet = new YanLoaderServlet();
MockServletConfig config = new MockServletConfig();
config.setServletContext(sc);
servlet.init(config);
final BankAccount acct = verifyBean(sc, "account");
servlet.destroy();
assertTrue("Destroyed", acct.isDestroyed());
}
public void testYanLoaderListenerWithDefaultContext() throws Exception {
MockServletContext sc = new MyServletContext("test/yan/web");
verifyListener(sc, "BankAccount");
}
public void testYanLoaderListenerWithCustomContext()throws Exception{
MockServletContext sc = new MyServletContext("test/yan/web");
sc.setInitParameter(YanLoader.CONFIG_FILE_PARAM, "/WEB-INF/yancontainer.xml");
sc.setInitParameter(YanLoader.USE_SPRING, "true");
verifyListener(sc, "ba");
}
private void verifyListener(ServletContext sc, String beanname){
ServletContextListener listener = new YanLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
final BankAccount acct = verifyBean(sc, beanname);
listener.contextDestroyed(event);
assertTrue(acct.isDestroyed());
}
private BankAccount verifyBean(ServletContext sc, String beanname){
Container yan = (Container)
sc.getAttribute(YanLoader.CONTAINER_ROOT);
assertNotNull(yan);
assertNotNull(sc.getAttribute(YanLoader.LIFECYCLE_MANAGER_ROOT));
final WebBankAccount acct = toWebBankAccount(yan.getInstance(beanname));
assertEquals(1000, acct.getBalance());
assertEquals("shark", acct.getId());
//assertEquals(beanname, acct.getBeanName());
assertFalse(acct.isDestroyed());
assertSame(sc, acct.getServletContext());
return acct;
}
private WebBankAccount toWebBankAccount(Object obj){
try{
return (WebBankAccount)obj;
}
catch(ClassCastException e){
throw new IllegalStateException("ClassCastException - classloader0="
+WebBankAccount.class.getClassLoader()
+", classloader1="+obj.getClass().getClassLoader());
}
}
}