Struts下配置log4j的方法(转帖2篇)

第一篇:转自:http://tech.eyeah.cn/3116/1113/1137/234119733.html

Log4J配置完后,tomcat5启动如此报错。

 作 者:程序员(onebelief)

 时 间:2005-02-26 12:30:08

 

log4j:WARN No appenders could be found for logge(org.apache.catalina.session.ManagerBase).

log4j:WARN Please initialize the log4j system properly.

讨教,讨教。

回复人:程序员(onebelief)2005-2-26 13:06:52

没有人知道么!?

回复人: throw new LowSalaryException(me) (kaymo)2005-2-26 14:08:36

一个包,2个配置文件

回复人:程序员(onebelief)2005-2-26 14:14:48

能说详细点儿么!?我是在架struts应用时出现的这个问题。

struts中的log4j怎么初始化!?

谢谢,请教完马上可以给分!

回复人:西门疯雪(bon_jovi)2005-2-26 14:30:51

log4j.jar和commons-logging.jar放到你的web应用底下的lib中。

在classes下建立两个配置文件commons-logging.properties和log4j.properties

commons-logging.properties里就一行,org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JCategoryLog说明用的是log4j。

启动tomcat就可以了。

你的类里面写日志都是调用的apache的接口,以后换其他日志系统也方便。

回复人:程序员(onebelief)2005-2-26 14:33:18

非常感谢

第二篇:转自:http://dev2dev.bea.com.cn/bbs/thread.jspa?forumID=121&threadID=4267&tstart=450

回复: 5   页数: 1   

gyokuho [普通用户]

发帖数: 9

活跃积分: 11

技术积分: 0

可用币值: 11

注册时间: 2002-9-4

用户状态:正常

 

 请教:Weblogic/Struts/Log4J 环境下,log destination(appender) 配置问题

提交时间: Jun 9, 2003 2:04:03 AM         引用  回复    发消息 

 

我用 Weblogic 7.0, Struts 1.1, commons-logging.properties 中只有一句:

    org.apache.commons.logging.Log=

        org.apache.commons.logging.impl.Log4JLog 

这样,输出到确省的 System.err去了。怎样配置才能指定输出到一个log文件?

查资料后,好像有:

  1, -Dlog4j.configuration=Log4JLog.properties

  2, 然后在 Log4JLog.properties 中写一些key=value。

什么的,在我的环境中试验后没有成功。请问具体需要怎样做才解决问题?

此文被gyokuho在2003/06/09 16:14:48修改!

--------------------------------------------------------------------------------

 

 

bea_ora [普通用户]

发帖数: 222

活跃积分: 225

技术积分: 3

可用币值: 240

注册时间: 2003-3-26

用户状态:正常

 

 Re:请教:Weblogic/Struts/Log4J 环境下,log destination(appender) 配置问题

提交时间: Jun 10, 2003 4:26:47 AM         引用  回复    发消息 

 

log4j里面有一个

log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.appender.R.File=example.log

log4j.appender.R.MaxFileSize=100KB

可以把log写到里面,具体的

你查一下log4j API 和

http://www.jfsys.com/main/service/service_log4j.htm

资料吧

此文被bea_ora在2003/06/09 20:31:02修改!

--------------------------------------------------------------------------------

 

 

gyokuho [普通用户]

发帖数: 9

活跃积分: 11

技术积分: 0

可用币值: 11

注册时间: 2002-9-4

用户状态:正常

 

 Re:请教:Weblogic/Struts/Log4J 环境下,log destination(appender) 配置问题

提交时间: Jun 11, 2003 4:30:25 AM         引用  回复    发消息 

 

多谢回复。

我在Log4j 的主页上也看到了这样的例子,但是自己试了几次,没有成功。

我不知道那些个设置应该放在哪个properties文件中,这个properties 文件

又应该放在什么位置。

希望做成功的同志给与指导。

--------------------------------------------------------------------------------

 

 

xutong [普通用户]

发帖数: 16

活跃积分: 15

技术积分: 1

可用币值: 10

注册时间: 2004-6-11

用户状态:正常

 

 Re: 请教:Weblogic/Struts/Log4J 环境下,log destination(appender) 配置问题

提交时间: Oct 25, 2005 4:01:05 PM         引用  回复    发消息 

 

../WEB-INF/class

--------------------------------------------------------------------------------

 

 

fengw [普通用户]

发帖数: 692

活跃积分: 695

技术积分: 60

可用币值: 590

注册时间: 2003-7-18

用户状态:正常

 

 Re: 请教:Weblogic/Struts/Log4J 环境下,log destination(appender) 配置问题

提交时间: Oct 25, 2005 4:47:14 PM         引用  回复    发消息 

 

需要在类路径下添加 log4j.properties文件。

下面是文件的内容,这个我就简单写了点,需要扩展的话查文档

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=debug,stdout

log4j.logger.com=warn,stdout

--------------------------------------------------------------------------------

让开,让开~~~~~~~

            ╭══╮

          ╭╯ΘΘ║

          ╰⊙═⊙╯。oо○-俺的灌水车来了!!

 

 

ttoc [普通用户]

发帖数: 58

活跃积分: 57

技术积分: 0

可用币值: 57

注册时间: 2005-8-27

用户状态:正常

 

 Re: 请教:Weblogic/Struts/Log4J 环境下,log destination(appender) 配置问题

提交时间: Oct 25, 2005 4:55:36 PM         引用  回复    发消息 

 

log4j.rootLogger=INFO,stdout,file

log4j.logger.com.common.utility.MailSend=ERROR,A1

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d %r [%t] %5p [%F:%L] - %m%n

log4j.appender.file=org.apache.log4j.RollingFileAppender

log4j.appender.file.File=c:/aaa.txt

log4j.appender.file.layout=org.apache.log4j.PatternLayout

log4j.appender.file.layout.ConversionPattern=%d %r [%t] %5p [%F:%L] - %m%n

log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

log4j.appender.rolling.layout.ConversionPattern=%d %r [%t] %5p [%F:%L] - %m%n

log4j.appender.rolling=org.apache.log4j.RollingFileAppender

log4j.appender.rolling.File=c:\comics.log

#log4j.appender.rolling.File=/usr/local/tomcat/logs/comics.log

log4j.appender.rolling.MaxFileSize=5120KB

log4j.appender.rolling.MaxBackupIndex=10

log4j.appender.A1=org.apache.log4j.RollingFileAppender

log4j.appender.A1.File=c:\mail.log

#log4j.appender.A1.File=/usr/local/tomcat/logs/comics.log

log4j.appender.A1.MaxFileSize=500KB

log4j.appender.A1.MaxBackupIndex=50

log4j.appender.A1.Append=true

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} - [%p] [%C{1}] - %m%n

 

 

一种知识交换的市场经济模式(幸福校园)

  今天,我想找一下struts下配置log4j的资料,结果发现一篇文章好像很好:(http://www.happycampus.com.cn/pages/2005/02/11/D160170.html)[计算机应用] Struts技术研究--Exception&Logging

  好不容易注了册,不过要人民币,没看成:(

  是一家韩国公司(http://www.agentsoft.co.kr/english/index.hcam)在经营,到他们主页需要下载韩文字体。http://www.happycampus.com.cn/。

  知识需要用钱去买,明码实价。我找到一篇论文,要求15HP,不知道折合人民币多少。花了10分钟注册,结果我注册后只有3HP,要求充值,人民币,至少10元,默认20元,银行汇款、网上支付。。。。

  对于习惯了在网上免费获取知识的我,真不适应。

  不过,这也算是一个知识共享的方式吧。

  好像他们做得还很成功。可以作为一种模式记在这里。

开发的路线不要走偏了

  现在的主要目标是解决学习网站已经知道的重大缺陷,这两天却做着做着去做试点技术了。想实践一种基于测试的结对编程模式。当然,实践是可以继续下去的,但前提是现有开发任务不能受大的影响。

  所以,在测试代码未作的情况下,是不是可以先把功能性的代码写完。

  也许,先进的不一定是适合于我们的。如果没有条件和必要,再丢掉我们的主要目标,可能是错误的选择。

  怎么办?

  可以这样办,测试代码是要试验的,不过好钢用在刀刃上,只在最需要测试的类才为其写单独的StrutsTestCase或Junit测试类。

  这也是一个折衷的办法吧。

  我们要在现实和理想中取得平衡,以实现我们的既定目标为准绳。

(转帖)网页色彩、图形的使用(Coloring Your World)

转自:http://www.cntesting.com/bbs/read.php?tid=1343&page=e#a

Coloring Your World

Robert Hess

Microsoft Corporation

July 10, 2000

Contents

Background Check

Graphic Formats

Applying Palettes

Image and color have had a long history on Web pages. But based on some of the questions that people send to me, as well as some of the results I see on far too many professionally designed Web pages, it seems to me that a lot of folks are still confused as to the technical aspects of how to use images and/or color on their pages. So, excuse me if the following is old news to some of you; I expect many people will find the following information useful.

Background Check

First, let me address what must be the simplest aspect of color usage, and possibly one of the most common problems present on many Web sites. When I say simple, I really mean simple. Here it is:

<body bgcolor="white">

Are you using this on your site? Are you sure? Take a moment to check your browser's default background color setting. If you are like the majority of computer users, you have your default background color set to white. Now, imagine what happens if—as you design Web pages—you constantly see them with a white background, even if you haven't specifically set the background to white. Now imagine that you add some graphics, or other page elements to your site. If you aren't intentionally checking to verify that these will still look fine on any background color, you should be sure to manually set your page's background color, because chances are that your carefully designed Web page won't look quite right if some color besides white comes in for the background.

<body>

</body> <body bgcolor="white">

</body>

Figure 1. The use of transparency in the lefthand image renders the accompanying text virtually unreadable. Also, the shadow around both the fly and the text looks jagged, because it was designed to be used on a white background. In the righthand image, the BGCOLOR attribute was explicitly set to white, so the image shows up as the designer intended.

I have my Web browser set to gray as the default background color, and you would be amazed by the number of sites I run across that weren't expecting to suddenly get a gray background. You would be equally surprised to see who owns some of these sites. Check it out. Change your default background color to something other than white, then browse the Web—starting with your own site.

Graphic Formats

Another fairly simple design issue, but one that I constantly see people struggling with, is the difference between .gif and .jpeg images. The specific issue is which format to use when you prepare images for your Web site.

The simple rule of thumb is that .jpeg images are best used for photographic (also known as "continuous tone") images, and the .gif format is best for images that have large areas of solid color. The reason for this lies in the process these formats use for their compression.

Figure 2. This 4K JPEG image would be 11K if saved as a GIF

Figure 3. This 2K GIF image would be 4K if saved as a JPEG

A .gif is a "lossless" compression model. This means that if you take an uncompressed bitmap image, compress it into a .gif file, then uncompress it back into a bitmap image, you will end up with the identical image. No bits are lost. However, if you were to convert this bitmap to a .jpeg, then bring it back to a bitmap, you would almost certainly lose data—and the tighter the compression, the more data you would lose. The algorithm that .gif uses for image compression works really well when you have a large area of a single color—but it will actually increase the size of the image if every pixel is a different color than the preceding one.

Figure 4. Zooming in on the above GIF image saved as a JPEG

Figure 5. Zooming in on the above GIF image

The only time you might need to use the .gif format for what otherwise might be best implemented as a .jpeg image is when you need transparency in your image. Graphic images are rectangular in form, but the .gif image format supports the notion of treating one of your image colors as trasparent, so that whatever image or color is underneath the image will show through. This is extremely handy for situations in which you want a non-rectangular image on your page. You can see this effect in the above "A Fly in the Ointment" example. The image of the fly and the shadowing are best done in a .jpeg image—but because I wanted to use transparency, I had to turn the image into a .gif.

Okay, there is one other time you would want to turn a .jpeg image into a .gif—when you want animation in your image. The .gif file format supports multiple images in a single file, and Web browsers have leveraged this to allow a .gif file to represent simple animation. However, I highly caution against using this too often.

Applying Palettes

When discussing the usage of .gif and .jpeg images, it is also important to touch upon the aspect of color palettes. A color palette is the definition of colors you will use for your image. The palette is placed and is then referenced by the appropriate color index within the image definition itself. This can allow the image data to be a lot smaller than it would be otherwise, but it also limits the numbers of colors you can use.

For example, let's pretend you had a 640x480 image that uses only 256 colors. If each pixel of the image is stored as a full, 24-bit color value (24 bits is the data storage required for a color value, such as "#99F5A2"), you end up with an image file that is about one megabyte in size. However, if you instead build a 256-entry color palette for each of those 24 bit colors— then, within your image file, use only 8-bit values (8 bits is the data storage required for an index value capable of referencing 256 different locations in a table) to indicate which of those 256 colors you want to use for your image, you end up with an image that is about one third the size. (Note that these calculations are on raw pixel images for discussion purposes only; an actual .gif or .jpeg image with these characteristics would be of considerably different size.)

Understanding the notion of palettes is important, because a .gif image uses palettes for its image definition, but .jpeg does not. This means that a .gif image can contain no more than 256 unique colors, while a .jpeg can contain virtually any color that can be described by a 24-bit value (more than 16 million colors). Most image-editing tools will allow you to customize/optimize the palette used by a .gif image, so that the colors in its palette will be those 256 colors that the image needs. A potential problem arises, however, when users set their display to 256-color mode. In that case, both the image and the display are using a color palette for showing images on the screen—and if an image wants to use a color that isn't contained in the screen's color palette, the nearest color from the screen's palette will be used instead.

While the palette the browser uses to display your image can't be controlled by the Web page being displayed, and, in fact, can't even be known by the Web page, it is possible to optimize a .gif image for display in a browser. You can do this by using a special browser-safe color palette. A long time ago, I wrote an article about this safety palette. Suffice it to say that by optimizing your images to use a specific set of 216 colors, you can exercise a fair amount of control over how your images will look in virtually any browser on any user's screen.

Figure 6. A black-and-white JPEG image that uses only 247 shades of gray

Figure 7. Dithering Mode: the same image, but dithered to use the Safety Palette

Figure 8. Nearest Color: the same image, but reduced to the nearest colors of the Safety Palette

In the example above, I've produced three black-and-white images of a Seattle ferry. The top image is a .jpeg, which will do a good job at reproducing the original black-and-white image. The image in the center is a .gif file to which I have applied the safety palette and a dithering algorithm to closely approximate the original image. If you are viewing this on a display set to 256-color mode, then both the top and center images will have the same grainy look to them. Otherwise, the topmost image will look fine and the center image will look grainy.

The image on the bottom is another .gif, in which I am exaggerating the problem by applying the safety palette and using a nearest-color algorithm. The result produces larger areas of color—true to the .gif format, but splotchy in this image. However, this .gif is smaller than the .jpeg on the top; the dithering of the center image causes it to be the largest of them all.

I've only scratched the surface of proper Web site use of images and color. I hope you have found something here that will help you design your Web sites just a little bit better.

昨晚,不小心女儿的左肘关节脱臼了

无意之中,轻轻的一拉。这是女儿的第四次关节脱臼吧。也是送到人民医院住院部骨科找医生复位的。今天,没让她去幼儿园,在家休养一天再说。免得她在幼儿园里跟别的小朋友玩时出问题。

原来小的时候,她只知道哭,现在她不会哭了,会跟我们说,左边手臂痛。

怎么样处理异常?

  处理异常有两种基本的方式:在程序内部捕获它并处理

    try{}

   catch(){}

   或者:在方法的异常规范中声明,告诉上一层的程序,本代码会掷出异常,请处理

  throws Exception{}

   但是,怎么样选择这两种方法呢?

  我看了一下thinking in java 3rd

  里面有一段关于处理方法的选择的话附于后:

  我觉得可以理解下面一些原则:

  1、目的:把处理异常的部分和功能部分分开,使系统易于理解和维护;

  2、原则:你如果不知道怎么处理一个异常就不要捕获它(而把它交给上级处理);

  3、但是具体的处理方式仍是灵活多变的,In this section we’ll look at some of the issues and complications arising from checked exceptions, and options that you have when dealing with them.

所以,我现在只有在利用原则2的情况下使代码尽可能的简单。

  4、最后那段话不大明白,好像是说从原来C风格的异常处理转过来的人会感到有很大的利益的改变,但是作者感到当它使用起来不大方便的时候又有点迷惑了。最后写了一句什么:“所以的模型都是错的,一些是有用的”。是什么意思?世上没有十全十美的方法吗?

Alternative approaches

An exception-handling system is a trap door that allows your program to abandon execution of the normal sequence of statements. The trap door is used when an “exceptional condition” occurs, such that normal execution is no longer possible or desirable. Exceptions represent conditions that the current method is unable to handle. The reason exception handling systems were developed is because the approach of dealing with each possible error condition produced by each function call was too onerous, and programmers simply weren’t doing it. As a result, they were ignoring the errors. It’s worth observing that the issue of programmer convenience in handling errors was a prime motivation for exceptions in the first place. Feedback

One of the important guidelines in exception handling is “don’t catch an exception unless you know what to do with it.” In fact, one of the important goals of exception handling is to move the error-handling code away from the point where the errors occur. This allows you to focus on what you want to accomplish in one section of your code, and how you’re going to deal with problems in a distinct separate section of your code. As a result, your mainline code is not cluttered with error-handling logic, and it’s much easier to understand and maintain. Feedback

Checked exceptions complicate this scenario a bit, because they force you to add catch clauses in places where you may not be ready to handle an error. This results in the “harmful if swallowed” problem:

try {

  // ... to do something useful

} catch(ObligatoryException e) {} // Gulp!

Programmers (myself included, in the first edition of this book) would just do the simplest thing, and swallow the exception—often unintentionally, but once you do it, the compiler has been satisfied, so unless you remember to revisit and correct the code, the exception will be lost. The exception happens, but it vanishes completely when swallowed. Because the compiler forces you to write code right away to handle the exception, this seems like the easiest solution even though it’s probably the worst thing you can do. Feedback

Horrified upon realizing that I had done this, in the second edition I “fixed” the problem by printing the stack trace inside the handler (as is still seen—appropriately—in a number of examples in this chapter). While this is useful to trace the behavior of exceptions, it still indicates that you don’t really know what to do with the exception at that point in your code. In this section we’ll look at some of the issues and complications arising from checked exceptions, and options that you have when dealing with them. Feedback

This topic seems simple. But it is not only complicated, it is also an issue of some volatility. There are people who are staunchly rooted on either side of the fence and who feel that the correct answer (theirs) is blatantly obvious. I believe the reason for one of these positions is the distinct benefit seen in going from a poorly-typed language like pre-ANSI C to a strong, statically-typed language (that is, checked at compile-time) like C++ or Java. When you make that transition (as I did), the benefits are so dramatic that it can seem like strong static type checking is always the best answer to most problems. My hope is to relate a little bit of my own evolution, that has brought the absolute value of strong static type checking into question; clearly, it’s very helpful much of the time, but there’s a fuzzy line we cross when it begins to get in the way and become a hindrance (one of my favorite quotes is: “All models are wrong. Some are useful.”). Feedback

(转)[提问] 这样的需求测试用例该怎么设计?(junit答案)

转自:http://www.cntesting.com/bbs/read.php?tid=623&fpage=1

[提问] 这样的需求测试用例该怎么设计?

心力背单词 [traffic /'træfik/ n. 交通(量) ]

到某论坛上逛了一圈,看到了这个提问正好是我的本行,所以特别拿出来秀以下,如果这个朋友到了我们这里可以直接问我。

原贴:

本地写卡功能:

界面:

号码、产品、副号、空SIM卡

号码和空卡为可输入框

1、号码不能是一卡双号的副号,可以是:全球通普通号码,全球通一卡双号主号(若有副号,直接把副号赋给副号输入框处)、神州行、动感地带

2、号码状态必须是正使用状态

3、SIM卡状态是可用状态

4、动感地带号码只能用“28动感地带空白SIM卡”,神州行只能用“29 神州行空白SIM卡”,全球通用“26全球通空白SIM卡”和“27 一卡双号空白SIM卡”;如果输入该号码有副号则只允许写“27 一卡双号空白SIM卡”;

符合1、2、3、4 写卡成功

若号码状态不对, 提示请用正使用的号码

若卡状态不对,提示请用可用状态的卡

若不符合1,提示副号不能写卡

若不符合4,提示卡类型不正确

 

 

测试是非常古老的传统行业,据说地球起源来自于一场非常糟糕的实验。根据我最新考证,上帝创造的亚当夏娃就没有经过很好的测试,不然怎么会因为一个APPLE_BUG就导致了整个世界的崩溃?! 

[楼 主] | Posted:2005-11-03 22:53|  

 

 

smile_xunn

 

 

级别: 测试新手

精华: 0

发帖: 2

测试威望: 2 点

测试币: 6 CSB

测试贡献值: 0 点

在线时间:5(小时)

注册时间:2005-11-08

最后登陆:2005-12-12       

--------------------------------------------------------------------------------

心力背单词 [sail /seil/ n. 帆,航行;vi. 航行,启航,翱游,飘;vt. 航行,飘过 ]

准备一些定义,如下:

全球通普通号码 commonCode

全球通一卡双号主号 doubleCode

神州行 allGo

动感地带 dyArea

号码状态 codeState

SIM卡状态 simState

28动感地带空白SIM卡 dyArea28

29 神州行空白SIM卡 allGo29

26 全球通空白SIM卡 doubleCode26

27 一卡双号空白SIM卡(无副号) doubleCode27

27 一卡双号空白SIM卡(有副号) doubleCode27Fu

测试java伪代码如下:

/**

* 定义一个Product Bean,由它来定义卡的类型,如下:

* 28动感地带空白SIM卡 dyArea28

* 29 神州行空白SIM卡 allGo29

* 26 全球通空白SIM卡 doubleCode26

* 27 一卡双号空白SIM卡(无副号) doubleCode27

* 27 一卡双号空白SIM卡(有副号) doubleCode27Fu

*/

public class Product{

  private String _productId = "commonCode";//产品编码,默认为全球通编码

  private String _productName = "全球通普通号码";//产品名称,默认为全球通描述

  public Product(String productId,String productName){

        this._productId = productId;

        this._productName = productName;

  }

  public Product(){

  }

 

}

/**

* 定义一个Card JavaBean.

*/

public class Card{

  private String _startCode = null;//号码

  private Product _product = null;//产品

  private String _endCode = null;//副号

  private boolean _isState = false;//卡状态

  public Card(String startCode ,Product product,String endCode,boolean isState ){

      this._startCode = startCode;

      this._product = product;

      this._endCode = endCode;

      this._isState = isState;

  }

  public void setStartCode(String startCode){

      this._startCode = startCode;

  }

  public String getStartCode(){

      return _startCode ;

  }

 

  public void setEndCode(String endCode){

      this._endCode = endCode;

  }

  public String getEndCode(){

      return _endCode;

  }

  public void setProduct(Product product){

    this. _product = product;

  }

  public Product getProduct(){

    return _product;

  }

  public void setIsState(boolean isState){

    this._isState = isState;

  }

  public boolean getIsState(){

    return _isState;

  }

  /* *

  * 对_startCode,_endCode进行代码检查,

  */

  public boolean isRightCode(){

    return false;//没有作代码实现,返回值为false;

  }

  /**

  * 得到代码范围,通过判断主号和辅号,判断该号码属于哪种卡,如“28动感地带    

  * 空白SIM卡”

  */

  pubic String getCodeType(){

    //未作实现代码返回值为空

    return null;

  }

}

/**

* 使用继承junit TestCase 的 CardTest类进行测试

*/

public Class CardTest extends TestCase{

  public void testWriteCard(Card card){

    //如果号码状态不对,提示请用正使用的号码

    assertTrue(card.getIsState(),"请用正使用的号码");

    //若卡状态不对,提示请用可用状态的卡

    assertTrue(card.isRightCode(),"请用可用状态的卡");

    // 如果输入该号码有副号则只允许写“27 一卡双号空白SIM卡”;

    if(card.getEndCode()!=null &&!card.getEndCode().trim().equals("")){

    card.getCodeType().equals("27 一卡双号空白SIM卡");

    }

    //1、号码不能是一卡双号的副号,可以是:全球通普通号码,全球通一卡双号主号     //(若有副号,直接把副号赋给副号输入框处)、神州行、动感地带

    String productName = card.getProduct().getProductName().;

   

    if(productName .equals("全球通普通号码")){

        //全球通用“26全球通空白SIM卡”和“27 一卡双号空白SIM卡”        

      if(!(card.getCodeType().equals("26全球通空白SIM卡")||

        card.getCodeType().equals("27 一卡双号空白SIM卡"))){

            assetFalse(true,"卡类型不正确");

      }

    } else if(productName.equals("全球通一卡双号主号")){

        //ok;

    }else if(prodcutName.equals("神州行")){

        //神州行只能用“29 神州行空SIM卡”          

        if(!card.getCodeType().equals("29 神州行空白SIM卡")){

            assetFalse(true,"卡类型不正确");

        }

    }else if(prodcutName.equals("动感地带")){

        //动感地带号码只能用“28动感地带空白SIM卡”

      if(!card.getCodeType().equals("28动感地带空白SIM卡")){

            assetFalse(true,"卡类型不正确");

      }

             

    }else{

        assertTrue(false,"副号不能写卡");

    }

    asserTrue(true,"写卡成功");

   

}

 

 

[转帖] 利用StrutsTestCase测试Struts应用程序

转自:http://www.cntesting.com/bbs/read.php?tid=1239

--------------------------------------------------------------------------------

[转帖] 利用StrutsTestCase测试Struts应用程序

心力背单词 [partly /'pa:tli/ ad. 部分地,在一定程度上 ]

作者:叶枫(http://blog.matrix.org.cn/page/叶枫)

关键字:Struts StrutsTestCase

一、Struts测试概述

 

  一个具有良好系统架构的J2EE应用程序至少有三层组成,即表现层,商业层和系统

集成层(包括数据存取以及和其他系统集成),目前,Struts是应用比较广泛,实现MVC2模式应用于表现层的一种技术. 在这里面,Struts Action主要用来完成一些简单的数据校验,转换,以及流程转发控制(注意:这里流程不是业务规则). 因此在对整个应用程序进行测试时,我们同时也要测试Struts Action.

  但是,测试Struts Action相对测试简单的JavaBean是比较困难,因为Struts是运行在Web服务器中, 因此要测试Struts Action就必须发布应用程序然后才能测试. 我们想象一下,对于一个拥有上千个JSP page和数百甚至数千Java Classes的大规模应用程序,要把他们发布到诸如Weblogic之类的应用服务器再测试,需要多少的时间和硬件资源? 所以这种模式的测试是非常费时费力的.

  所以,如果有一种办法能够不用发布应用程序,不需要Web服务器就能象测试普通Java Class一样测试Struts Action,那就能极大地加强Struts的可测试性能,使应用程序测试更为容易,简单快速. 现在这个工具来了,这就是StrutsTestCase.

二、StrutsTestCase 概述

  StrutsTestCase 是一个功能强大且容易使用的Struts Action开源测试工具,

它本身就是在大名鼎鼎的JUnit基础上发展起来的。因此通过和JUnit结合

使用能极大加强应用程序的测试并加快应用程序的开发.

 

  StrutsTestCase提供了两者测试方式,模仿方式和容器测试方式. 所谓模仿方式就是有StrutsTestCase本身来模拟Web服务器. 而容器测试方式则需要Web服务器. 本文要讨论的是前者,原因很简单,不需要Web服务器就能象测试普通的Java Class一样测试Struts Action.

三、准备StrutsTestCase和Struts Action/ActionForm/Config

  StrutsTestCase是一个开源工具,可以到http://strutstestcase.sourceforge.net下载. 目前最新版本是2.1.3,

如果你使用Servlet2.3就下载StrutsTestCase213-2.3.jar,使用Servlet2.4的就下载StrutsTestCase213-2.4.jar.

另外StrutsTestCase本身就是从JUnit继承的,所以你还需要下载JUnit3.8.1.

  在本文中,我们用一个简单的例子来做测试. 假设我们有一张表Hotline(country varchar2(50),pno varchar2(50)),

我们要做的是根据输入条件从这张表检索相应的记录.检索条件是country.

Value Object: 

package sample;            public class HotlineDTO implements Serializable{        private String country = "";       private String pno = "";                /**         * Method HotlineActionForm         *         *         */        public HotlineDTO () {             super();      }                public void setCountry(String country) {                this.country = country;         }        public void setPno(String pno) {                this.pno = pno;         }        public String getCountry() {                return (this.country);         }        public String getPno() {                return (this.pno);         }              }

ActionForm:

     

package sample;      import org.apache.struts.action.ActionForm;      public class HotlineActionForm extends ActionForm{        private String country = "";        private String pno = "";                /**         * Method HotlineActionForm         *         *         */        public HotlineActionForm() {                super();        }                public void setCountry(String country) {                this.country = country;         }        public void setPno(String pno) {                this.pno = pno;         }        public String getCountry() {                return (this.country);         }        public String getPno() {                return (this.pno);         }              } 

Action Class:

     public class SearchHotlineAction extends Action {     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,      HttpServletResponse response) throws Exception {        String target = "";        try{         //调用HotlineDAO检索hotline         String country=((HotlineActionForm)form).getCountry();         List hotlineList = HotlineDAO.getHotlineList(country);         if(hotlineList!=null && hotlineList.size()>0){            request.setAttribute("hotlineList",hotlineList);            target = "hotlineList";         }else{            target = "notfound";         }        }catch(Exception ex){           ....        }                             }

Struts Config:

 

<struts-config>      <form-beans>     <form-bean name="hotlineActionForm" type="sample.HotlineActionForm" />       .......   </form-beans>  <action-mappings>     <action path="/SearchHotline"           name="hotlineActionForm"           type="sample.SearchHotlineAction "                     scope="request"                                                      validate="false">       <forward name="hotlineList" path="/hotlineList.jsp"/>              <forward name="notfound" path="/searchHotline.jsp"/>   </action>    .....  <action-mappings>   ........ <struts-config>

四、初试StrutsTestCase

    当采用模拟方式时,所有的StrutsTestCase测试Class都是从MockStrutsTestCase继承下来的.

    下面我们就创建一个最简单的测试Class.

   

public class SearchHotlineAction extends MockStrutsTestCase {     public void setUp()throws Exception{     }     public void tearDown()throws Exception{     }    public void testSearchHotline() throws Exception{    setRequestPathInfo("/SearchHotline.do");    addRequestParameter("country", "CN");    actionPerform();    }    }

   上面的Class相信用过JUnit的朋友都很熟悉.

    好了,一个简单的测试例子就完成了,如果你用的是Eclipse就选择Run-Run...-JUnit-New就可以直接运行.不需要发布你的程序,不需要任何的Web服务器支持,就可以测试Struts Action,这就是StrutsTestCase带来的好处.下面简单地介绍一下它是怎么工作的.

    在上面的例子中,我们调用setRequestPathInfo()告诉StrutsTestCase我们要模拟JSP调用SearchHotline.do这个Action,并且调用addRequestParameter()增加了一个参数country.最后调用actionPerform()运行.

看到这里,大家发现一个问题没有? 在上面Action的源代码里我们是通过

String country=((HotlineActionForm)form).getCountry();

也就是ActionForm来取得输入的参数值,可我们在testSearchHotline()方法里并没有设置ActionForm?

那么它是怎么出来的呢? 其实大家如果熟悉Struts的运行流程的话就知道,JSP接受用户的输入并发请求时

都是类似这样的http://hostname/servletName?param1=value1¶m2=value2. 只是Struts接受到这些

参数后再根据Struts Config里的Action和ActionForm的映射把他们转为ActionForm后传给Action的.

   在上面的例子,我们只是简单地运行了Action,那么Action是否正确执行以及返回的结果是不是我们想要的呢?

我们继续完善一下testSearchHotline()这个Method.

public void testSearchHotline() throws Exception{

    setRequestPathInfo("/SearchHotline.do");

    addRequestParameter("country", "CN");

    actionPerform();

    verifyNoActionErrors();

    verifyForward("hotlineList");

    assertNotNull(request.getAttribute("hotlineList"));

    List hotlineList = (List) request.getAttribute("hotlineList");

    for (Iterator it = hotlineList.iterator();it.hasNext();){

     ....

    }

    }

我们在actionPerform()后增加了几行语句来断定Struts Action是否正确执行.

   verifyNoActionErrors() -- 判断Action里没有任何的Action;

   verifyForward("hotlineList") -- 判断Action确实转发到hotlineList;     

   assertNotNull(request.getAttribute("hotlineList")) -- 判断Action确实返回了hotlineList并且不为空

到这里,我们已经基本上讨论完了StrutsTestCase的核心部分. 从头到尾,我们没有发布应用程序,也不需要Web服务器,对我们来讲,Struts Action就象普通的Java Class一样容易调试测试.这就是StrutsTestCase给我们带来的方便.

五、深入StrutsTestCase

  除了以上我们用到的几个断定和校验方法外,StrutsTestCase还提供了其他几个方法便于我们测试Struts Action. 下面我一一讲述,具体的大家可以参考文档.

verifyActionErrors/Messages --  校验ActionActionServlet controller 是否发送了ActionError或ActionMessage.   参数为ActionError/Message Key

verifyNoActionErrors/Messages --校验ActionActionServlet controller 没有发送ActionError或ActionMessage

VerifyForward -- 校验Action是否正确转发到指定的ActionForward.

VerifyForwardPath -- 校验Action是否正确转发到指定的URL

verifyInputForward -- 校验Action是否转发到Action Mapping里的input属性

verifyTilesForward/verifyInputTilesForward--和以上类似,应用程序使用到tiles时用的

六、关于Web.xml和Struts-Config.xml

  缺省情况下,StrutsTestCase认为你的Web.xml和struts-config.xml的路径分别是:

  /WEB-INF/web.xml和/WEB-INF/struts-config.xml

  1. 假如你的web.xml/struts-config.xml的路径是

  d:/app/web/WEB-INF/web.xml(struts-config.xml)的话,就需要把d:/app/web加到classpath.

 

  2. 假如你的struts config是strust-config-module.xml,

  那么必须调用setConfigFile()设置你的struts config文件

 

七、结束语

  J2EE应用程序的测试在开发过程中占有相当重要的位置,利用StrutsTestCase能极大方便你测试基于Struts的应用程序.

关于作者:

叶枫:热爱Java和Oracle. 在软件开发有近10年, 目前在国外一家美国大公司担任SA, 负责技术研究。

网站访问中断3天

  由于空间提供商ip变化的缘故,网站中断访问3天,今天早上由他们把问题解决了。

  但是,我修改了域名管理中的密码后就一直不能进入域名管理,正在咨询提供商:www.java-cn.com

  我觉得他们以往的服务还是基本上可以的。