51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 3190|回复: 0
打印 上一主题 下一主题

[转贴] How to write test cases in java with JUnit

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2007-12-27 19:35:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
What is a test case
There are many ways to write test cases. Overall, we can say a test case is a code fragment that programmatically checks that another code unit - a method - functions as expected. In order to make the testing process an efficient one, it is recommended to use a testing framework. There are two major java testing framework.

JUnit is written by Eric Gamma of the GoF fame and Kent Beck. JUnit has long been un-unchallenged in the testing framework arena.
TestNG, written by Cedric Beust is a newer framework, which uses innovative concepts, much of which have been picked up by JUnit in the 4.x versions.
Using a framework to develop your test cases has a number of advantages, most important being that others will be able to understand test cases and easily write new ones and that most development tools enable for automated and / or one click test case execution. Which of the frameworks you'll choose, that's a matter of personal preference. Both enable you to properly test your code, are equally well supported by Java development tools that matter and both are easy to use. In this article we'll address only JUnit test case development issues.

How to Write Test Cases with JUnit
If you're using a version earlier then JUnit 4, it is mandatory for your test case to inherit from the TestCase class, like in the following code example:

        public class ExampleTestCase extends TestCase {
                ...
        }

JUnit Coding Conventions
A JUnit test case can contain multiple tests. Each test is implemented by a method. The declaration of a test method must comply to a set of conventions in order to help JUnit and associated tools to automate the discovery and execution of tests. These conventions are:

the name of the method must begin with "test", like in "testCreateUser",
the return type of a test method must be null,
a test method must not throw any exception,
a test method must not have any parameter.
Suppose you need to test the following method: public User createUser(String userName, String password1, String password2) throws PasswordDeosntMatchException { ... }. A typical test case for this method could look like this:

    public class CreateUserTestCase extends TestCase {
        public void testCreateUser() {
            ...
        }

        public void testCreateUserFailPasswordDoesntMatch() {
            ...
        }
    }

How to Write a Success Test With JUnit
Why write three tests for one single method, you may ask? Well, this will be better explained in the article that explains how to develop test cases. For now, let's just say that you must not only test that your method works as expected under normal conditions, but also that it fails as expected when current environment configuration requires it.

The first method will simply call the method then compare the returned object with the provided parameters if the user was properly created. To compare the result with reference values you should use the assert family of methods. Also, we must not forget to force the test to fail if the exception is thrown when it is not supposed to. Here is how you could implement "testCreateUser()":

    public void testCreateUser() {
        try {
            User ret = instance.createUser("john", "pwd", "pwd");

            // use assertEquals to compare the name
            // of the returned User instance with the reference value
            assertEquals(ret.getUserName(), "john");

            // use assertEquals to compare the pasword
            // of the returned User instance with the reference value
            assertEquals(ret.getPassword(), "pwd");
        } catch (PasswordDeosntMatchException e) {
            // force the test to fail, because the exception was thrown
            // and it shouldn't have
            fail();
        }
    }

The assertEquals method will compare the two provided values and if they're not equal, it will generate an internal exception which will inform JUnit about the failure. Also, if PasswordDeosntMatchException is thrown - knowing that this should not happen with the set of parameters we have provided - the fail() method will have the same effect. In either case, JUnit will mark the test as failed and report it as such. You can pass a message to the assertEquals and fail methods. This message will be shown in the report when that particular assertion fails, helping developers to more easily identify errors. This feature can be particularly helpful if you maintain a large test base each with many assertion points.

How to Write a Failure Test With JUnit
To make sure PasswordDeosntMatchException is thrown if the two versions of the password don't match, we can use the following test method:

    public void testCreateUser() {
        try {
            User ret = instance.createUser("john", "pwd1", "pwd2");

            // fail because the exception should have been thrown
            // but it obviously hasn't been
            fail();
        } catch (PasswordDeosntMatchException e) {
            // do nothing: the test is a success because the exception was thrown as expected,
            // given the set of parameters we have provided.
        }
    }

JUnit Errors
If a test method throws a RuntimeException JUnit will report an error. A JUnit error is different from a JUnit failure in that a failure is detected by the testing logic while an error is caused by an unexpected, rather technical, malfunction.

The Life Cycle of a JUnit Test Case
There are a few details of which you should be aware of when writing JUnit tests. First of all, when executing a test case, JUnit will instantiate the test case class as many time as there are test methods. That is, each test method will be executed on a different instance of the test case class. Before calling the test method, JUnit will call the setUp() method. The tearDown method will be called after the test method completes - successfully or not. The setUp() and tearDown() methods should be used to create and then clean up the test environment.
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-11-14 20:30 , Processed in 0.073789 second(s), 26 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

快速回复 返回顶部 返回列表