JUnit is a widely used Java unit testing framework, but it does not provide the support of parametric testing, many testers have to write the test data in the program or other methods to achieve the separation of data and code, in the subsequent modification and maintenance of a lot of restrictions and inconvenience. Feed4junit is an open source, JUnit-based extension that allows users to easily store test data in files or other data sources by using annotations provided by Feed4junit. Through introduction and simple examples, this article makes the reader understand and be able to use Feed4junit to easily implement the test of data and code separation.
Feed4junit and JUnit
Often, there are a number of such interfaces in the business logic of the application: they accept different inputs, then perform or validate, or process, and then complete the same process. For example, the login portal of the website, the user name and password are limited in length, but also have the restrictions on whether to allow special characters, so in the course of our unit testing, according to the different length of the user name and password, as well as different character combinations, only need to provide the same test code structure, can complete the test, Different only test data and expectations, but because the input parameters in each test method are different, we must write a separate test case for each input group, resulting in a lot of redundant code, very inconvenient to maintain.
Based on the above scenario, JUnit 4 provides parameterized features that enable testing of the same test code for different data inputs, as shown in Listing 1:
Listing 1. JUnit 4 Parameterized Test code example
package sample.test;import static Org.junit.assert.assertequals;import java.util.Arrays; Import Java.util.collection;import Org.junit.test;import Org.junit.runner.runwith;import Org.junit.runners.parameterized;import Org.junit.runners.parameterized.parameters;import sample.code.UserAccess ;/* * junit-parameter Test Sample */@RunWith (Parameterized.class) public class Junitsample {private String user;private S Tring Pw;private Boolean expected, @Parameterspublic static Collection Datagenerater () {return arrays.aslist (new object[ [] {{"User01", "123456", True},{"HelloWorld", "123456", False},{"David", "Re*ads", false}, {"Goodone", "Onegood", true});} Public junitsample (string user, String pw, Boolean expected) {This.user = USER;THIS.PW = pw;this.expected = expected;} @Testpublic void Testaccesscheck () {assertequals (expected, Useraccess.accesscheck (user, PW));}}
As can be seen from the example code above, JUnit 4 produces data by using a static method of Collection for the return type of a tag @Parameters comment, and the test data is passed through the variable to the test method to complete the test of the multi-data input. However, as the needs of the business, testers need to constantly increase the test data and modify existing test data, JUnit 4 provides hard-coded method has become more cumbersome and inconvenient, data and code separation is particularly important.
Fortunately, the feed4junit described in this article is a good solution to the problem of separating data from code, and Feed4junit is an extension of the JUnit test framework, which makes your unit tests easier to write and maintain by manipulating test data from files and different data sources.
This article will show you an example of the installation of feed4junit and the implementation of test code and data separation, and note that the sample code for this article is all based on the class for a very simple user login test, and if you are using Eclipse as your IDE, look at the listing 2 class of code:
Listing 2. Instance class
Package Sample.code;public class UserAccess {//simple validation for user name and Passwordpublic static Boolean Accessch Eck (String userName, string password) {if (Username.length () <= 4 | | username.length () > 8) return false;if (password . Length () <= 4 | | Password.length () > 8) return false;if (Username.contains ("@") return False;if (Password.contains ("*")) return False ; return true;}}
Back to top of page
Download and installation of Feed4junit
1. Feed4junit is an open source test component, you can download the latest version from the following link:
http://sourceforge.net/projects/feed4junit/files/
2. Unzip the downloaded zip package, copy the entire Lib folder to the root directory of your Java project, 1:
Figure 1. Copy Lib to the project root directory
3. Select the project, right-click on the properties of the project, and add all the jars under the Lib folder in step 2 to the project's Build Path under Add JARs 2
Figure 2. Add Jar to Build Path
With the three steps above, you have prepared your FEED4JUNIT environment and can start using it, of course, before developing the test code, you must import the feed4junit corresponding package into your class.
Back to top of page
Testing for data-to-code separation using Feed4junit
Feed4junit data sources can include the following types-Files (CSV or Excel), databases, custom data sources.
Feed4junit uses a special run class Feeder.class to support and identify parameterized tests, and if you want to write test scripts that separate data from code, you must add a comment @RunWith (feeder.class) to your test class. At the same time, you need to use @Test to mark the way you implement the test, and use @Source to declare and receive data from the data source, as shown in Listing 3:
Listing 3. Basic code structure
Package Sample.test;import static Org.junit.assert.assertequals;import Org.databene.feed4junit.feeder;import Org.databene.benerator.anno.source;import org.junit.test;import org.junit.runner.runwith;/* * feed4junit-@RunWith, @Test and @Source */@RunWith (Feeder.class)//specify The class would be the RAN as feeder Classpublic class Feed4jsample {@Test Specify the method as a test Method@source ()//specify the input data sourcepublic void Testaccesscheck () {assertequals ( True, True);}}
Take a file as a data source
Feed4junit supports reading data from CSV or Excel files as input, here we take an Excel file as an example.
1. Create the Data.xls data file in the root of the test project, sample Data 3, by default, the first row exists as a column name and is not read as data during the run.
Figure 3. Excel Data source
2. Create a test class and declare the data source as a @Source ("Data.xls") on the test method that receives the data, and the data in Excel will automatically match the position of the column and the parameters of the test method during delivery, and read and pass to the test method body as a unit. The value of the user column in the 3 is passed into the method body as the first argument of the method, and the value of the PW column acts as the second parameter of the method, and so on. During the test, the Excel file is first read in a row (with three columns), then the data is passed into the method body in the order of location (each column is in order for one parameter) to be executed, and the next line in Excel is read to test the same process, and the principle of Java is very similar to the iterators in. Note that when the number of columns in the data file is less than the number of test method parameters, the test fails because of a location mismatch.
Listing 4 includes an example of reading and passing data from CSV and Excel:
Listing 4. File Data Source Example
Package Sample.test;import static Org.junit.assert.assertequals;import Org.databene.benerator.anno.source;import Org.databene.feed4junit.feeder;import Org.junit.test;import Org.junit.runner.runwith;import sample.code.useraccess;/* * Feed4junit-get Data from Csv/excel File source */@RunWith (Feeder.class) public class F4jfromf ile {@Test @source ("Data.csv")//csv sourcepublic void Testaccesscheck_csv (String userName, String pw, Boolean expected) { Assertequals (expected, Useraccess.accesscheck (UserName, PW));} @Test @source ("Data.xls")//excel sourcepublic void Testaccesscheck_excel (String userName, String pw, Boolean expected) { Assertequals (expected, Useraccess.accesscheck (UserName, PW));}}
3. Run the test because Feed4junit is an extension of junit, so it runs in exactly the same way as JUnit, which is run as JUnit, as shown in result 4, and we can see that the data in Data.xls has all passed into the test method and runs.
Figure 4. Run results example with database as data source
By using @Database, you can easily use data from a database, which is useful when testing a large amount of test data or reusing existing application business data as test data.
When you use a data source from a database, you must first use @Database declare the database information, you can add @Database comments for the class or method, and if the annotation class is @Database, all methods in the class can use the data of this database as the source, when declaring @ Only this method in this class can call the database as the data source when the method is being used. @ Database has some properties for declaring information for connecting to the database, take a look at the description:
ID: An identifier used to identify the database data source, which is associated with a reference in the @Source of the test method
URL: The URL of the database
Driver: Database Driver
User: Username for database
Password: password for the database
After you have completed the definition of the above database, you need to reference the library you need in the @Source of the test method, using the property ID and selector to do this:
ID: The ID in the @Source corresponds to the ID of the @Database
The Selector:sql statement, which is used to query out the appropriate data to pass to the test method
Here we use DB2 as the data source, using the DB2 Sample database, and creating a table named Test to store the test data, and the test data is exactly the same as the Excel data source in Figure 3, see Figure 5.
Figure 5. Test data in a data table
First, create a test class, add @Database comments and increase the connection information for the database, specify an ID that represents the database, associate it with an ID in the @Source of the test method, and make a selector statement for the data query, for example, selector = "s Elect * from Test, which takes all the data from the test table for testing, please refer to the following code example for details:
Listing 5 declares @Database on the class.
Listing 5. Declare @Database on a class
Package Sample.test;import static Org.junit.assert.assertequals;import Org.databene.benerator.anno.database;import Org.databene.benerator.anno.source;import Org.databene.feed4junit.feeder;import Org.junit.Test;import Org.junit.runner.runwith;import sample.code.useraccess;/* * Feed4junit-get Data from Database, all test methods can use The database Data */@RunWith (Feeder.class) @Database (id = "TestDB", url = "Jdbc:db2://localhost:50000/sample", Driver = "C Om.ibm.db2.jcc.DB2Driver ", user =" Db2admin ", password =" Db2admin ") public class F4jfromdb {@Test @source (id =" TestDB ", SE lector = "SELECT * from TEST") public void Testaccesscheck (string userName, String pw, string expected) {Boolean bsucess = Useraccess.accesscheck (Username.trim (), Pw.trim ()), Assertequals (Expected.trim (), bsucess.tostring ());}}
Listing 6 is to declare the @Database on the method:
Listing 6. Declare the @Database on the method
/* Feed4junit-get data from Database, only the specified method can use the Database Data */@RunWith (Feeder.class) public class F4jfromdb_method {@Test @database (id = "TestDB", url = "Jdbc:db2://localhost:50000/sample", Driver = "COM.IBM . db2.jcc.DB2Driver ", user =" Db2admin ", password =" db2admin ") @Source (id =" TestDB ", selector =" SELECT * from TEST ") publi c void Testaccesscheck (String userName, String pw, string expected) {Boolean bsucess = Useraccess.accesscheck (username.tr Im (), Pw.trim ()); Assertequals (Expected.trim (), bsucess.tostring ());}}
During the test run, the data connection is established through url,driver and other information, the data request is sent through the selector, the final query is completed and the data is passed to the test method, and the data is matched with the parameters in the order of the data table, and the running result is similar to Figure 4.
Custom Data sources
In addition to the data sources for Csv,excel and databases, Feed4junit also provides a custom data source to meet the needs of different users, and users can also complete the data-derived definition by encapsulating the parameterized tests provided by JUnit 4, all of which the authors no longer detail, Users can encapsulate and obtain data from different data sources and pass them to the corresponding interface of Feed4junit to complete the customization of the data source.
Conclusion
This paper comprehensively explains the Feed4junit test support for data and code separation by comparing the introduction and the simple and understandable examples. By providing simple annotations, Feed4junit enables users to implement data-and code-separation testing with great ease, greatly enhancing the usability of the JUnit test framework. I believe you have seen its merits in the narrative of this article. At the same time, this article is only part of the test enhancements provided by Feed4junit, and Feed4junit also provides a number of features such as random testing of large amounts of data and equivalence class testing, if you are interested in your own reference.
Reprint-Java unit test for data and code separation using Feed4junit