Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file from WEB-INF in a JUNIT test

In a controller of a webapp, I am redirecting to some other page (xyz.jpsx) when a given condition is true.

Now, in a Junit test, I want to enforce that the redirect is done correctly, but also that the redirect points to a jsp that actually exists.

I couldn't find a way, inside a Junit, to read files from inside WEB-INF. I don't want to hardcode the fullpath as the solution wont be much portable.

I totally understand the fact that files in WEB-INF are out the classpath, but there might be a way to access theses files. Looking for a portable solution that will also work on my integration server.

like image 465
pmartin8 Avatar asked Sep 24 '15 13:09

pmartin8


1 Answers

There is great NIO.2 API in JDK 1.7 with class Path, with help of this class you can easily access to folder with your JSPs (without any ServletContexts or whatever) and do what you need with list of JSP files, here is little sample for you:

import org.junit.Test;

import java.io.File;
import java.nio.file.Paths;

public class WebInfAccessTest
{
    @Test
    public void shouldListJsps()
    {
        File jspFolder = Paths.get("src/main/webapp/WEB-INF/pages").toFile();
        for (File jsp : jspFolder.listFiles())
            System.out.println(jsp.getName());
    }

}

======================================================================
Here is result for my test Maven project
======================================================================
$ mvn test
...
 T E S T S
-------------------------------------------------------
Running WebInfAccessTest
add.jsp
get.jsp
list.jsp
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.073 sec
like image 97
CroWell Avatar answered Oct 08 '22 14:10

CroWell