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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With