JBUILDER2005 Unit test Creation test firmware _jsp programming

Source: Internet
Author: User
Creating a test firmware in a test case through Setup (), teardown () allows the test firmware to be used by the different test methods of a single test case, and if multiple test cases require the same test firmware, the test firmware needs to be extracted into a separate class. JBuilder provides 3 predefined test firmware classes, respectively:

· JDBC Test firmware (jdbc Fixture): A test firmware for obtaining a database connection, which allows users to obtain data connections in a convenient way by setting up some database information.

· Jndi Test firmware (Jndi Fixture): Used to simulate a test firmware that obtains an object from a Jdni environment.

• Compare test firmware (comparision Fixture): Output the test to an external file for comparison at the second Test.

• Custom test firmware (custom Fixture): User-defined test firmware.

If you are well aware of the JUnit framework structure, perhaps these JBuilder extended test firmware are of little significance to you, and they are nothing more than building a common test environment that you can write yourself. In this section, we introduce two test firmware.

   JDBC Test firmware

If your project already has a common class to get data connections, you also need to build a JDBC test firmware, because JDBC test firmware can be specified directly directly by creating a Test Case wizard, in addition, the JDBC test firmware also provides a number of test-oriented methods.

To create the JDBC test firmware, we first create a Jdatastore database whose data file is located in/db/hr.jds, and the username and password of the database is: sysdba/123456. The HR.JDS database has a table of employee, which is structured as follows:

Wrong figure! Text with no specified style in the document. Data for Employee tables

Employee has 3 fields, ID, name, and age, string, string, and int, and fills in 3 records as shown above.

To demonstrate the specific use of the JDBC test firmware, we design two business classes: Employee and EmployeeDAO, and then use the JDBC test firmware to provide a data connection for the test EmployeeDAO. The code for these two classes is as follows:

Code Listing Error! Text with no specified style in the document. Employee.java class

1. Package chapter25.db;
2. public class Employee
3. {
4. Private String ID;
5. Private String name;
6. private int age;
7. Public Employee (string ID, string name, int age) {
8. this.id = ID;
9. this.name = name;
This.age = age;
11.}
A. Public String getId () {
return ID;
14.}
Public String GetName () {
return name;
17.}
public int getage () {
return-age;
20.}
public boolean equals (Object o) {
if (o instanceof Employee) {
Employee e1 = (employee) O;
Return Id.equals (E1.getid ()) && name.equals (E1.getname ()) &&age = = E1.getage ();
.} else {
return false;
27.}
28.}
29.}

The employee class is used to describe a record of the employee table that accesses the EmployeeDAO code of the database as follows:

Code Listing Error! Text with no specified style in the document. Employeedao.java class

1. Package chapter25.db;
2. Import java.sql.*;
3. public class EmployeeDAO
4. {
5. Private Connection Conn;
6. Public EmployeeDAO (Connection conn) {
7. this.conn = conn;
8.}
9. Public Employee FindByID (String id) throws SQLException
10. {
String sqlstr = "SELECT * FROM employee WHERE id = '" +id+ "";
Statement stat = conn.createstatement ();
ResultSet rs = stat.executequery (SQLSTR);
if (Rs.next ()) {
Return to New Employee (id,rs.getstring ("name"), Rs.getint ("Age"));
}else{
return null;
18.}
19.}
20.}

To save space, we provide only one way to access the database: FindByID (), which is to find the employee object by ID.

Below, we use the JBuilder Wizard to create a JDBC test firmware:

1. File->new...->test-> on the Test page, double-click the JDBC fixture icon to launch the Create Wizard, which looks like this:

Wrong figure! Text with no specified style in the document. Specify JDBC Test firmware class name

Specify the class name for the JDBC test firmware in class name: Hrjdbcfixture, accept the other default settings, press next to next.

2. Set up information about the connection database.

In this step, JBuilder provides most of the database driver selection and connection information settings, and its dialog box looks like this:



Wrong figure! Text with no specified style in the document. Specify database connection Information

· Driver: Select the Borland.databstore.jdbc.DataStoreDriver class. The JDBC Test firmware provides support for most databases. The database drive classes that are temporarily unavailable in the dropdown box are displayed in red, and you can make them available by configuring the Engineering Extensions Class library.

· URL: Click on the following ... button, the Create URL for Datastore dialog box is displayed, as shown in the following figure:

Wrong figure! Text with no specified style in the document. To construct a dialog box for the Datastore data connection URL

The settings for this dialog box change depending on the type of database. For the Jdatastore database, the dialog box provides two options for using the first setting item if the database file is placed on the local computer, or the second setting. We choose the first option, click on the following ... button, navigate to/db/hr.jds and select it, press OK to return to the Main Wizard dialog box window.

· User NAME:SYSDBA.

· password:123456.

Test the connection by following the test connection in the dialog box, and you should return a success information report that the connection test succeeded. Click Finish to create the JDBC test firmware, whose code looks like this:

Code Listing Error! Text with no specified style in the document. Hrjdbcfixture.java


1. Package fixture;
2. Import java.sql.*;
3. Import java.io.*;
4. Import Com.borland.jbuilder.unittest.JdbcFixture;
5. public class Hrjdbcfixture
6. Extends Jdbcfixture
7. {
8. Public hrjdbcfixture (Object obj) {
9. Super ();
Super.seturl ("Jdbc:borland:dslocal:d:/jtjb2005/chapter25/db/hr.jds");
Super.setdriver ("Com.borland.datastore.jdbc.DataStoreDriver");
Super.setusername ("Sysdba");
Super.setpassword ("123456");
14.}
15.
public void SetUp () {
Super.setup ();
18.}
19.
public void teardown () {
Super.teardown ();
22.}
23.}


The JDBC Test firmware inherits Com.borland.jbuilder.unittest.JdbcFixture, and the important methods of this class include:

Dumpresultset (): A resultset is directed to a writer that accepts two parameters, one is resultset and the other is writer.

getconnection (): Gets a data connection.

Runsqlbuffer (): Executes the SQL statement that is cached in the StringBuffer object.

Runsqlfile (): Executes the SQL statement saved in the file and specifies the address of the SQL file by entering the parameter.

Setdriver (): Sets the JDBC drive.

SetUrl (): Sets the URL of the data connection.

setusername (): Sets the user name.

SetPassword (): Set password.

Tips:

Create Jdatastore JDBC Test firmware through the wizard, Although you can select the Com.borland.datastore.jdbc.DataStoreDriver drive directly in the dialog box, when you run this JDBC test firmware, JBuilder reports the error message: java.lang.ClassNotFoundExcept Ion:com.borland.datastore.jdbc.DataStoreDriver. It was jbuilder. When you create a JDBC test firmware from a wizard, you do not load the drive class directly into the engineering library, so you need to manually pass the Project->project properties...->paths Add the Jdatastore class library item in the JBuilder class library to the Engineering class library.

Because the data for the employee table may change as the test progresses, it is difficult to test the rules when testing, because rules must be developed based on an assumed environment. For example, now that we're testing the FindByID () method, we have to know what data is in the employee table, so you have to create some specific data at the beginning of the test. Since the JDBC firmware can execute SQL saved in an external file, we create a insert.sql file, place it under/db/insert.sql, and the contents of the file are as follows:


Delete from Employee;insert into employee values (' 0004 ', ' Dashan '); INSERT into employee values (' 0005 ', ' wa ',); insert into employee values (' 0006 ', ' Koming ', 31);


When running this SQL statement, empty the data in the employee table before inserting 3 specific records. Next, we create the Testemployeedao test case class that applies the JDBC test firmware.

1. Activates the EmployeeDAO in the editor.

2. File->new...->test-> Double-click the test case icon to start the wizard that created the test cases, create a test case named Testemployeedao for EmployeeDAO in the 1th and 2 steps of the wizard. This test case carries out functional testing of the EmployeeDAO FindByID () method.

3. In step 3rd of the wizard, select the test firmware, and the hrjdbcfixture that we created earlier in the wizard dialog box already appears in the list. You can also through the dialog box add ... and remove to select different test firmware.


Wrong figure! Text with no specified style in the document. Select Test Firmware

Press Finish to create the Testemployeedao test case directly, and the code looks like this:

Code Listing Error! Text with no specified style in the document. Testemployeedao.java, the test case class created by the wizard

1. Package chapter25.db;
2. Import junit.framework.*;
3. Import fixture.*;
4. Import java.sql.*;
5. Public class Testemployeedao extends TestCase {
6. Private EmployeeDAO EmployeeDAO = null;
7. Hrjdbcfixture Hrjdbcfixture;
8. protected void SetUp () throws Exception {
9. Super.setup ();
/** @todo Verify the constructors*/
EmployeeDAO = new EmployeeDAO (null);
Hrjdbcfixture = new Hrjdbcfixture (this);
Hrjdbcfixture.setup ();
14.}
15.
protected void teardown () throws Exception {
EmployeeDAO = null;
Hrjdbcfixture.teardown ();
Hrjdbcfixture = null;
Super.teardown ();
21.}
22.
public void Testfindbyid () throws SQLException {
String id = ";
Employee Expectedreturn = null;
Employee Actualreturn = Employeedao.findbyid (ID);
Assertequals ("Return value", Expectedreturn, Actualreturn);
/** @todo fill in the test code*/
29.}
30.}


The test case instantiates the Hrjdbcfixture object in the Setup () method and invokes its setup () method to initialize the environment. The JDBC Test firmware's setup () is its initialization method only if JDBC tests the firmware's setup (13th) method to invoke other methods of the JDBC test firmware, such as getconnection (). Here's what we can do to transform this Testemployeedao, as shown in the bold code below:

Code Listing Error! Text with no specified style in the document. After the transformation of the Testemployeedao class


1...
2. Public class Testemployeedao extends TestCase {
3...
4. protected void SetUp () throws Exception {
5. Super.setup ();
6. hrjdbcfixture = new Hrjdbcfixture (this);
7. Hrjdbcfixture.setup ();
8. EmployeeDAO = new EmployeeDAO (Hrjdbcfixture.getconnection ());
9. Hrjdbcfixture.runsqlfile ("D:/jtjb2005/chapter25/db/insert.sql", true);
10.}
11...
public void Testfindbyid () throws SQLException {
Employee Expectemp = new Employee ("0004", "Dashan", 23);
Employee realemp = Employeedao.findbyid ("0004");
Assertnotnull (realemp);
Assertequals (expectemp,realemp);
17.}
18.}


Because the JDBC test firmware requires other methods to be available after the Setup () method call, in the Testemployeedao Setup () method, we move the EmployeeDAO instantiation method to the back, In order to instantiate the EmployeeDAO, you can get the data connection (line 8th) by Hrjdbcfixture.getconnection (). On line 9th, execute the Insert.sql file, clear the original data from the table, and insert 3 rows of test data.

On line 13th to 14th, the EmployeeDAO FindByID () method is used to find the employee object that returns an ID of 0004, and two test rules are set on line 15th to 16th.

Run this test case with the JDBC test firmware, hrjbdcfixture the test firmware to prepare the test environment before performing the Testemployeedao Testfindbyid () test method.

   Compare Test firmware

The comparison firmware is used to record the current Test record for comparison with the next output. The comparison firmware class inherits from Com.borland.jbuilder.unittest.TestRecorder, and the Testrecorder class inherits Java.io.Writer. So if you need to use writer output information when testing, you can consider using the comparison firmware, which provides a lot of easy-to-use output information methods. You can use the wizard to create a comparison firmware.

Testrecorder a total of 4 constant record modes, respectively:

· UPDATE: Compare the firmware to the current output information and the existing information file, if the file does not exist, create a new file, record output information.

· COMPARE: Compares the current output information of the firmware with the information that already exists.

· Record: Compares the current output information of the firmware log, overwriting if there is already an output file present.

· OFF: Turns off the Compare firmware feature.

Attention:

After creating the record file, suppose you have changed the test case or test suite, you will need to reinitialize the output file: Set the Testrecorder output mode to a recording, create the file, and then adjust it to update. The output data file is a binary file, placed in the same directory as the source program file, and has the same name as the test case class.

The following are common methods for testing your firmware, as described below:

Boolean print (String s)

Prints a string with Testrecorder and returns False if the pattern is a record and the string is inconsistent with the original. You can set a test rule like this:

Asserttrue (Recorder.print (result.tostring ())

Boolean println (String s)

Similar to print (), except to add a newline.

boolean compareobject (Object o)

The Equals () method of the incoming object is invoked and compared with the object previously recorded with Recordobject ().

Boolean recordobject ()

Record an object for comparison by calling the Compareobject () method later.

Next, we create a comparison firmware and apply this comparison firmware to create a test case for the employee class.

1. File->new...->test-> on the Test page, double-click the Comparision fixture icon to start the wizard that creates the comparison firmware class, and the dialog box looks like this:

Wrong figure! Text with no specified style in the document. Specify comparison firmware name and attributes

· Class Name: Tests the firmware class name to accept the default ComparisionFixture1.

· Echo output to console: The test firmware outputs the information to the console of the test run at the same time.

· Verbose output: The test firmware outputs detailed information.

Additionally, Save comparision data in this directory specifies the location where the output information file is to be compared, which can be passed ... Button changes, here we accept the default settings. Press OK to create a comparison firmware class directly, your code looks like this:

Code Listing Error! Text with no specified style in the document. Comparisonfixture1.java, Wizard-created test firmware class

1. Package fixture;
2. Import Com.borland.jbuilder.unittest.TestRecorder;
3. Public class ComparisonFixture1 extends Testrecorder
4. {
5.
6. Public ComparisonFixture1 (Object obj) {
7. Super ();
8. Super.setmode (UPDATE);
9. Super.setverbose (True);
Super.setecho (TRUE);
One. String fileName = Super.constructfilename ("d:/jtjb2005/chapter25/test", obj);
Super.setoutputfile (FileName);
13.}
14.
public void SetUp () {
16.}
17.
public void teardown () {
19.}
20.}

Line 8th sets the mode to update, and the 9th, 10 lines set the Output property. Line 11th to 12th specifies the directory of the output file.

2. Create a Testemployee test case class.

file->new...->test-> on the test page, double-click the test case icon to start the Create Test Cases Wizard and create the Testemployee test case class for the employee class and constructor. In step 1th of the wizard, you will see the following dialog box:

Wrong figure! Text with no specified style in the document. Select the constructor for the test employee class

Click Next until the 3rd step of the wizard:

The list lists all of the test firmware for the project, selects Hrjdbcfixture, clicks Remove the firmware, leaves only the ComparisionFixture1 firmware, and clicks Finish to create the Testemployee test Case class's code framework directly, Based on the code framework, the employee is tested with the comparison firmware, and its final code looks like this:

Code Listing Error! Text with no specified style in the document. Test cases that apply comparison firmware

1. Package chapter25.db;
2.
3. Import junit.framework.*;
4. Import fixture.*;
5.
6. Public class Testemployee extends TestCase {
7. Private employee employee = NULL;
8. ComparisonFixture1 ComparisonFixture1;
9.
protected void SetUp () throws Exception {
Super.setup ();
Employee = new Employee ("0004", "Harry", 23);
ComparisonFixture1 = new ComparisonFixture1 (this);
Comparisonfixture1.setup ();
15.}
16.
protected void teardown () throws Exception {
Employee = NULL;
Comparisonfixture1.teardown ();
ComparisonFixture1 = null;
Super.teardown ();
22.}
23.
public void Testemployee () {
String id = "0004";
-String name = "Harry";
int age = 23;
Comparisonfixture1.print (Employee.getid ());
Comparisonfixture1.recordobject (employee);
Employee = new Employee (ID, name, age);
Asserttrue (Comparisonfixture1.print (Employee.getid ()));
Asserttrue (Comparisonfixture1.compareobject (employee));
33.}
34.}

An employee object is instantiated on line 12th, the ID value of the original employee object is maintained and printed on line 28th, compared in line 31st, the original employee object is recorded in the 29th line, and the two objects are compared in the 31st line.

Running the Testemployee class, you will see the output information in the Test Output tab of the test run, and in the folder where the test case is located, an output file employee will be created with no suffix.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.