Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize servletContext in junit test

Tags:

tomcat

In my project, I initialized configuration data in ServletContext, then I can read data from memory, and it worked well, but now I wrote some junit tests, it can not initialized ServletContext. can you tell me how to do?

like image 586
bright.liang Avatar asked Mar 22 '23 06:03

bright.liang


2 Answers

There is a way to mock servlet:How to mock servlet in spring mvc, but I think you need not initialize configuration data in servletContext, you can use A static variable to store configuration data, and when you start server you can initialized it. the code is as follows:

public class InitProperties {

private static Logger logger = Logger.getLogger(InitProperties.class);

public static Map<String, String> propertiesMap = new HashMap<String, String>();

public static void initProperties(){
    String filePath = FilePathConstant.XXX_CONF;
    Properties props = new Properties();
    InputStream in = null;
    try {
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        props.load(in);

        Set keySet = props.keySet();

        for(Object o: keySet){
            propertiesMap.put(o.toString(), props.getProperty(o.toString()).toString());
        }
    } catch (Exception e) {
        logger.error("Read property value by key failed!", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            logger.error("Close inputStream failed!", e);
        }

    }
}

}

you just need call the methodInitProperties.initProperties() when you start server, and then you can read configuration data from InitProperties.propertiesMap.

like image 72
bright Avatar answered Apr 15 '23 03:04

bright


I think you need not initialize configuration data in servletContext, you can use A static variable to store configuration data, and when you start server you can initialized it.
For setting up a full WebApplicationContext in a test environment, you can use XmlWebApplicationContext (or GenericWebApplicationContext), passing in an appropriate MockServletContext instance.
You might want to configure yourMockServletContext with a FileSystemResourceLoader in that case, to make your resource paths interpreted as relative file system locations.

like image 38
Elton Wang Avatar answered Apr 15 '23 01:04

Elton Wang