`

StrutsTestCase的使用

阅读更多

StrutsTestCase for JUnit v2.1.4

(2008-12-03 13:57:37)
<script></script>标签:

it

 

StrutsTestCase for JUnit v2.1.4

Now supporting Struts 1.2 and 1.3, including Tiles and Sub-Applications!

Questions? Comments? Check out the user forums.

Support This Project

What is it?

StrutsTestCase for JUnit is an extension of the standard JUnit TestCase class that provides facilities for testing code based on the Struts framework. StrutsTestCase provides both a Mock Object approach and a Cactus approach to actually run the Struts ActionServlet, allowing you to test your Struts code with or without a running servlet engine. Because StrutsTestCase uses the ActionServlet controller to test your code, you can test not only the implementation of your Action objects, but also your mappings, form beans, and forwards declarations. And because StrutsTestCase already provides validation methods, it's quick and easy to write unit test cases.

StrutsTestCase is compliant with the Java Servlet 2.2, 2.3, and 2.4 specifications, and supports Struts 1.2/1.3, and Cactus 1.7 and JUnit 3.8.1.

Please note that StrutsTestCase is no longer backwards compatible with Struts 1.0. The last release compatible with Struts 1.0 is StrutsTestCase v2.0.

Where does it live?

StrutsTestCase for JUnit is hosted at SourceForge. You can find the latest and greatest release of StrutsTestCase here.

Javadocs for all of the StrutsTestCase classes can be found here, and there is also a discussion forum and a list of frequently asked questions.

Mock Testing vs. In-Container Testing

There are two popular approaches to testing server-side classes: mock objects, which test classes by simulating the server container, and in-container testing, which tests classes running in the actual server container. StrutsTestCase for JUnit allows you to use either approach, with very minimal impact on your actual unit test code. In fact, because the StrutsTestCase setup and validation methods are exactly the same for both approaches, choosing one approach over the other simply effects which base class you use!

StrutsTestCase for JUnit provides two base classes, both of which are extensions of the standard JUnit TestCase. MockStrutsTestCase uses a set of HttpServlet mock objects to simulate the container environment without requiring a running servlet engine. CactusStrutsTestCase uses the Cactus testing framework to test Struts classes in the actual server container, allowing for a testing environment more in line with the actual deployment environment.

Please note that while the following examples use the MockStrutsTestCase approach, you could choose to use the Cactus approach by simply subclassing from CactusStrutsTestCase without changing another line of code!

How does it work?

Please note that the StrutsTestCase distribution comes with these and other examples, as well as step-by-step instructions for running them -- see the README file in the examples directory for more details. As well, there are many more methods in the StrutsTestCase library than are illustrated here -- check out the javadocs for a complete picture of what you can do with StrutsTestCase!

Using the popular cookbook approach, let's consider the following code snippet:

public class LoginAction extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String username = ((LoginForm) form).getUsername(); String password = ((LoginForm) form).getPassword(); ActionErrors errors = new ActionErrors(); if ((!username.equals("deryl")) || (!password.equals("radar"))) errors.add("password",new ActionError("error.password.mismatch")); if (!errors.empty()) { saveErrors(request,errors); return mapping.findForward("login"); } // store authentication info on the session HttpSession session = request.getSession(); session.setAttribute("authentication", username); // Forward control to the specified success URI return mapping.findForward("success"); }

So, what are we doing here? Well, we receive an ActionForm bean which should contain login information. First, we try to get the username and password information, and then check to see if it is valid. If there is a mismatch in the username or password values, we then create an ActionError message with a key to a message catalogue somewhere, and then try to forward to the login screen so we can log in again. If the username and password match, however, we store some authentication information in the session, and we try to forward to the next page.

There are several things we can test here:

  • Does the LoginForm bean work properly? If we place the appropriate parameters in the request, does this bean get instantiated correctly?
  • If the username or password doesn't match, do the appropriate errors get saved for display on the next screen? Are we sent back to the login page?
  • If we supply the correct login information, do we get to the correct page? Are we sure there are no errors reported? Does the proper authentication information get saved in the session?
StrutsTestCase gives you the ability to test all of these conditions within the familiar JUnit framework. All of the Struts setup -- which really amounts to starting up the ActionServlet -- is taken care of for you.

 

So, how do we actually do it? Let's start by creating an empty test case, which we extend from the base StrutsTestCase class:

public class TestLoginAction extends MockStrutsTestCase { public void setUp() { super.setUp(); } public void tearDown() { super.tearDown(); } public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() {} }

NOTE: If you choose to override the setUp() method, you must explicitly call super.setUp(). This method performs some important initialization routines, and StrutsTestCase will not work if it is not called.

The first thing we need to do is to tell Struts which mapping to use in this test. To do so, we specify a path that is associated with a Struts mapping; this is the same mechanism that the Struts tag library method uses.

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setRequestPathInfo("/login"); } }

NOTE: By default, the Struts ActionServlet will look for the file WEB-INF/struts-config.xml, so you must place the directory that contains WEB-INF in your CLASSPATH. If you would like to use an alternate configuration file, please see the setConfigFile() method for details on how this file is located.

Next we need to pass form bean properties, which we send via the request object (again, just as Struts does):

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setRequestPathInfo("/login"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); } }

Finally, we need to get the Action to do its thing, which just involves executing the actionPerform method:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setRequestPathInfo("/login"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); } }

That's all you have to do to get the ActionServlet to process your request, and if all goes well, then nothing will happen. But we're not done yet -- we still need to verify that everything happened as we expected it to. First, we want to make sure we got to the right page:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setRequestPathInfo("/login"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); verifyForward("success"); } }

It's worth noting here that when you verify which page you ended up at, you can use the Struts forward mapping. You don't have to hard code filenames -- the StrutsTestCase framework takes care of this for you. Thus, if you were to change where "success" pointed to, your tests would still work correctly. All in the spirit of Struts.

Next, we want to make sure that authentication information was stored properly:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setRequestPathInfo("/login"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); verifyForward("success"); assertEquals("deryl",(String) getSession().getAttribute("authentication")); } }

Here we're getting the session object from the request, and checking to see if it has the proper attribute and value. You could just as easily place an object on the session that your Action object expects to find. All of the servlet classes available in the StrutsTestCase base classes are fully functioning objects.

Finally, we want to make sure that no ActionError messages were sent along. We can use a built in method to make sure of this condition:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setRequestPathInfo("/login"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); verifyForward("success"); assertEquals("deryl",(String) getSession().getAttribute("authentication")); verifyNoActionErrors(); } }

So, now that we've written one test case, it's easy to write another. For example, we'd probably want to test the case where a user supplies incorrect login information. We'd write such a test case like the following:

public void testFailedLogin() { addRequestParameter("username","deryl"); addRequestParameter("password","express"); setRequestPathInfo("/login"); actionPerform(); verifyForward("login"); verifyActionErrors(new String[] {"error.password.mismatch"}); assertNull((String) getSession().getAttribute("authentication")); }

Now, this looks quite similar to our first test case, except that we're passing incorrect information. Also, we're checking to make sure we used a different forward, namely one that takes us back to the login page, and that the authentication information is not on the session.

We're also verifying that the correct error messages were sent. Note that we used the symbolic name, not the actual text. Because the verifyActionErrors() method takes a String array, we can verify more than one error message, and StrutsTestCase will make sure there is an exact match. If the test produced more error messages than we were expecting, it will fail; if it produced fewer, it will also fail. Only an exact match in name and number will pass.

It's that easy! As you can see, StrutsTestCase not only tests the implementation of your Action objects, but also the mappings that execute them, the ActionForm beans that are passed as arguments, and the error messages and forward statements that result from execution. It's the whole enchilada!

Testing Tiles in Struts 1.2

The Tiles framework, which is integrated into Struts 1.2, is a flexible templating mechanism designed to easily re-use common user experience elements. StrutsTestCase now provides support for testing applications that use Tiles, allowing any test case to verify that an Action object uses the correct Tiles definition. Tiles testing is similar to calling verifyActionForward, with a twist:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setConfigFile("/WEB-INF/struts-config.xml"); setRequestPathInfo("/login.do"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); verifyTilesForward("success","success.tiles.def"); } }

This is similar to our previous test cases, except that we're additionally passing in a definition name to verify that this Action uses a given Tiles definition when resolving the expected forward. If it uses a different Tiles definition, or if the expected definition does not exist, then this test will fail. Additionally, you can call verifyInputTilesForward to verify that an Action uses an input mapping, and that input mapping is the expected Tiles definition:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setConfigFile("/WEB-INF/struts-config.xml"); setRequestPathInfo("/login.do"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); verifyInputTilesForward("success.tiles.def"); } }

Testing Sub-Applications in Struts 1.2

Struts 1.2 introduces the concept of sub-applications, or modules -- a powerful mechanism for dividing an application into functional components. StrutsTestCase now provides support for testing sub-applications, which extends the concepts discussed in the previous examples. The general idea is still the same: you can point a unit test to a configuration file, execute an action, and validate the results. The methods for setting the configuration file and executing an action are a little different, however, as the following example shows:

public class TestLoginAction extends MockStrutsTestCase { public TestLoginAction(String testName) { super(testName); } public void testSuccessfulLogin() { setConfigFile("mymodule","/WEB-INF/struts-config-mymodule.xml"); setRequestPathInfo("/mymodule","/login.do"); addRequestParameter("username","deryl"); addRequestParameter("password","radar"); actionPerform(); verifyForward("success"); assertEquals("deryl",(String) getSession().getAttribute("authentication")); verifyNoActionErrors(); } }

As you can see, this looks very similar to our other test cases. The first important difference is in setting the configuration file. Here, we set the files and associate this configuration file with a given sub-application name. This allows the StrutsTestsCase library to pass this configuration information so that the ActionServlet can correctly identify the sub-application. Note that the same rules apply to setting the CLASSPATH to locate the configuration file as those mentioned above.

The other important difference is in setting the request path information. Here, we set not only the path information, but also the sub-application names. The combination of these two parameters is equivalent to the entire request path; in our test case above, this would be equivalent to a path like this: /mymodule/login.do. It is important to note that when using this method, the first argument must contain only the sub-application name, and the second argument must contain the rest of the path not including the sub-application name. Otherwise, the request path will be incorrectly constructed, resulting in a spurious test failure.

分享到:
评论

相关推荐

    StrutsTestCase工程例子

    1. **Test Classes**:这些是使用StrutsTestCase编写的测试类,它们继承自`org.apache.struts.util.TestBean`或`org.apache.struts.action.ActionForm`,并覆盖了需要测试的方法。测试类会创建Action对象,设置输入...

    StrutsTestCase-2.1.4(含文档、源码、官方示例).rar

    这个压缩包“StrutsTestCase-2.1.4(含文档、源码、官方示例).rar”包含了StrutsTestCase的2.1.4版本,提供了丰富的资源来帮助用户理解和使用这个测试框架。 首先,我们来看"StrutsTestCase示例(含详细步骤)....

    strutsTestCase所需要用到的jar

    strutsTestCase所需要用到的jar org.springframework.core-3.1.2.RELEASE.jar spring-test.jar struts2-junit-plugin-2.3.16.3.jar xmlbeans-2.3.0.jar xmlpull-1.1.3.1.jar xstream-1.4.2.jar xwork-core-2.3.16.3....

    JakartaStrutsLive

    - **Cactus模式**:介绍Cactus模式下的StrutsTestCase使用方法。 #### 使用jWebUnit测试JSP - **功能测试**:讲解如何借助jWebUnit工具进行JSP页面的功能测试。 ### 工作于ActionForms和DynaActionForms #### 定义...

    Jakarta Struts Live

    - **使用StrutsTestCase(Cactus Mode)**:解释了如何在Cactus模式下使用StrutsTestCase进行测试,该模式可以与Servlet容器集成,提供更接近实际运行环境的测试体验。 - **使用jWebUnit测试JSP**:介绍了如何使用...

    Checked and Unchecked Exception

    在Java编程语言中,异常处理是一项关键特性,用于在程序执行过程中捕获并处理错误或非正常情况。...在使用StrutsTestCase或其他工具进行开发和测试时,正确处理这两类异常是确保代码质量、提高软件可靠性的重要手段。

    Struts2框架单元测试代码

    测试类通常继承自`StrutsTestCase`或`StrutsSpringTestCase`(如果使用了Spring框架),这两个类提供了模拟Struts2上下文环境的功能。 以下是一些可能的测试步骤: 1. **创建测试类**:创建一个Java类,例如`...

    struts2-junit-plugin-2.1.6.jar

    在使用`struts2-junit-plugin`时,开发者可以创建一个继承自`StrutsTestCase`的测试类,这个基类提供了对Struts2环境的模拟,使得测试无需依赖实际的Web服务器。测试用例可以通过`setUp()`方法设置必要的环境,然后...

    Spring整合Struts

    这种方式允许你集中管理所有的Spring上下文文件,对于使用如StrutsTestCase这样的测试工具尤其有用。因为StrutsTestCase的MockStrutsTestCase不会在启动时初始化监听器,所以将所有上下文文件放置在插件中是一种变通...

    struts2-junit-plugin-2.1.8.1.jar

    在测试方法上使用`@Test`注解,并可以使用`@Action(value = "your-action-name")`来指定要测试的Struts2 Action。 例如: ```java import org.apache.struts2.StrutsTestCase; import org.junit.Test; public ...

    Struts的高级应用

    使用StrutsTestCase,可以编写模拟HTTP请求的测试用例,提高代码质量。 5. **StrutsMSG**:这部分可能指的是Struts的国际化和本地化支持。在Struts中,可以创建资源文件(如Messages.properties)来存储各种语言的...

    精通Struts基于MVC的Java Web设计与开发 孙卫琴 光盘

    内容推荐 Struts是目前非常流行的基于MVC的Java ...第19章到第21章介绍了如何采用第三方软件,如Apache Common Logging API、Log4J、ANT和StrutsTestCase,来控制Struts应用的输出日志、管理以及测试Struts应用项目。

    精通 Struts:基于 MVC 的 JavaWeb 设计与开发(PDF)

    Struts是目前非常流行的基于MVC的Java Web框架。...第19章到第21章介绍了如何采用第三方软件,如Apache Common Logging API、Log4J、ANT和StrutsTestCase,来控制Struts应用的输出日志、管理以及测试Struts应用项目。

    基于MVC的java Web设计与开发

    Struts是目前非常流行的基于MVC的Java Web框架。...第19章到第21章介绍了如何采用第三方软件,如Apache Common Logging API、Log4J、ANT和StrutsTestCase,来控制Struts应用的输出日志、管理以及测试Struts应用项目。

    精通Struts_基于MVC的Java Web设计与开发

    Struts是目前非常流行的基于MVC的Java Web框架。...第19章到第21章介绍了如何采用第三方软件,如Apache Common Logging API、Log4J、ANT和StrutsTestCase,来控制Struts应用的输出日志、管理以及测试Struts应用项目。

    精通struts:基于mvc的java web设计与开发part3

    Struts是目前非常流行的基于MVC的Java Web框架。...第19章到第21章介绍了如何采用第三方软件,如Apache Common Logging API、Log4J、ANT和StrutsTestCase,来控制Struts应用的输出日志、管理以及测试Struts应用项目。

Global site tag (gtag.js) - Google Analytics