Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I test Servlets with JUnit?

I saw Jetty has got and ServletTest class which you can use to test Servlets.

tester = new ServletTester();
tester.setContextPath("/");
tester.addServlet(TestServlet.class, "/servlet/*");
... 
tester.start();

Do you know if there is something similar in Tomcat? How could I test a servlet?

like image 540
yeraycaballero Avatar asked Feb 10 '10 09:02

yeraycaballero


People also ask

Which methods Cannot be tested by JUnit test class?

Which methods cannot be tested by the JUnit test class? Explanation: When a method is declared as “private”, it can only be accessed within the same class. So there is no way to test a “private” method of a target class from any JUnit test class.

How do I run a test in JUnit?

Create Test Runner Class It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter. Compile the Test case and Test Runner classes using javac. Now run the Test Runner, which will run the test case defined in the provided Test Case class. Verify the output.

What can you test with JUnit?

JUnit is a Java unit testing framework that's one of the best test methods for regression testing. An open-source framework, it is used to write and run repeatable automated tests.


3 Answers

HttpUnit has a has a "simulated container" called ServletUnit.

like image 173
dbrown0708 Avatar answered Nov 08 '22 06:11

dbrown0708


Take a look at Jakarta Cactus

Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters, ...).

Here's a servlet test how-to

like image 21
Bozho Avatar answered Nov 08 '22 04:11

Bozho


I've never found a benefit to testing servlets directly (nor Struts actions, say), especially given the work needed to do it.

Most of my servlets/actions/whatever use POJOs for the bulk of their work, and the POJOs are heavily tested. The webapps themselves have suites of HtmlUnit tests. Everything in between I assume to be just plumbing.

I don't believe that I've even once encountered any sort of bug that would have ONLY been caught by testing the servlet classes directly, and which would not be caught by the POJO or webapp tests.

like image 2
Rodney Gitzel Avatar answered Nov 08 '22 06:11

Rodney Gitzel