Advanced usage of JUNIT4 unit testing

Source: Internet
Author: User

The JUnit unit test framework is an essential test tool for Java program Development, and now the most common is JUNIT4, where all the test cases in JUNIT4 use the form of annotations, which is more flexible and convenient than Junit3. Prior to the company's training course on unit testing, the lecturer only described the use of JUNIT4 's basic life-cycle-related annotations, including @beforeclass, @Before, @Test, @After, @AfterClass these annotations, These are sufficient to deal with simple unit tests, but there are many more complex and often encountered test requirements that rely on these lifecycle annotations and cannot be completed! So this share will show you another new world of JUNIT4, and look at the statement ...

In fact, in the unit testing training course, the lecturer did not talk about the core of JUNIT4, such as why JUnit does not have the main () method to run (because we know that no matter what the program must have a program entry, and it is usually main); What is the core component of JUnit, for example? How do I change the behavior of JUnit to get data and perform tests while running unit tests? More specifically, if I want to test a method that requires two parameters, how do I test the method using all permutations of the parameters I provide? If I need to test only the use cases related to a particular class in the vast test case, what to do ....

Before this, correct a little bit------JUNIT4 can run one of our methods directly, without the main entry function being flatly. As I told her about spring to a sister of our group, in the test method, add Spring (compent annotations or add a member variable for the class) to the class where the test method is located. Resource annotations are not egg-free. That is, spring does not scan the test class at all, nor does it inject property values for this class. Why do you say that? Because spring is initiated by a method that is labeled by @before in the test class, the JVM has instantiated this test class, which is not instantiated by spring, and Spring is a step behind, so there are no instances of this class in the Spring container. So JUNIT4 really have the main method? Yes, since it can run our method directly, it will certainly provide the JVM with its own program entry. In fact, under the Org.junit.runner package, there is a junitcore.class, which has a standard main method, which is the JUnit entry function. In this case, it is actually the same as the way we run our tests directly in our own Main method.

What I'm going to talk about is the new world of the JUnit test framework, or its core components, and what the lecturer doesn't say but is very useful------Runner, the JUnit runner!

Runner is just an abstract class that represents the tool used to run the JUnit test case, through which you can run the tests and inform the results of the notifier run. Usually we can use the @runwith annotation on top of the class where the method is being tested to specify a specific runner for this test class. In many cases, however, we did not do this because we used JUnit's default runnner------blockjunit4classrunner. When we do not add @runwith annotations to the test class, we are actually using this runner, which as the default runner only provides us with a basic junit life-cycle-based test note. With more unconventional testing requirements, we need to add @runwith annotations to the test class and specify specific runner to complete! Some of the more useful runner are listed below.

First, Suit------It can be used to perform a full range of test cases in multiple classes, for example:

@RunWith (Suite.  Class) @SuiteClasses ({person.  Class, people. class})  Public class testsuitmain{  //Although this class is empty, you can still run the JUnit test, which will execute all the test yongming in Person.class and//people.class once, at run time! }

Second, parameterized------in the ordinary unit test by the @test annotation label test method can only be public void, and can not have any input parameters. And that often bothers us, because sometimes we need to enter parameters for the test method, or even specify multiple parameters to be tested in bulk. At this time parameterized this runner can satisfy our request, the usage is as follows:

@RunWith (parameterized.class) Public classtestgenerateparams{PrivateString greeting; PublicTestgenerateparams (String greeting) {Super(); This. greeting = Greeting; } @Test Public voidTestparams () {System.out.println (greeting); }/** * Here The return should be an iterated algebraic group, and the method must be public static * @return */@Parameters Public StaticList Getparams () {returnArrays.aslist (Newstring[][]{{"Hello"},{"Hi"},{"Good Morning"},{" How is You"}}); }}

Category------inherited from suit, more powerful, it allows us to classify the methods tested in the test class, such as the person object has some properties, these properties have the Get/set method, while there are some common methods. We can classify the Get method and the normal method of obtaining the property to test. Such as:

 Public classpersontest{@Category (Attributefun.class) @Test Public voidTestgetage () {intAge = Person.getage ();    Assertequals (3, age); } @Category (Attributefun.class) @Test Public voidTestgetname () {String name = Person.getname (); Assertequals ("Willard", name); } @Category (Behaviorfun.class) @Test Public voidTesttalk () {String message = Person.talkto ("Jimy");    Assertnotnull (message); } @Category (Behaviorfun.class) @Test (timeout=200) Public voidTestwalk () {person.walk (); }}//The corresponding test execution code is as follows:@RunWith (Categories.class) @SuiteClasses (persontest.class) @IncludeCategory (Attributefun.class) Public classcategorytest{//Note that if you do not add @includecategory annotations, you have the same effect as using suit. }

Four, theories------although the meaning of the principle or speculation, but I am here in a more intuitive way to express it: provide a set of parameters of the permutation values as the input parameters of the method. Also note that when using theories this runner, our test methods can have input parameters, which are not available in other runner. Here is an example:

@RunWith (theories.class) Public classtheoriestest{@DataPoint Public StaticString nameValue1 = "Tony"; @DataPoint Public StaticString nameValue2 = "Jim"; @DataPoint Public Static intAgeValue1 = 10; @DataPoint Public Static intAgeValue2 = 20; @Theory Public voidTestMethod (String name,intAge) {System.out.println (String.Format ("%s ' s age is%s", name, age)); }}

The above code means that the "Tony", "Jim", 10, and 204 parameters are passed to the pending method in a type-valid permutation. Therefore, the result of the output must also have 2x2=4 species:

Tony ' s age is 10

Tony ' s age is 20

Jim ' s age is 10

Jim ' s age is 20

However, for the sake of simplicity, in addition to using @datapoint annotations to provide parameters, you can also provide parameters by @datapoints annotations, referring to the above code, only need to replace the four field parameters of the @datapoint annotation callout with the following two:

@DataPointspublicstatic string[] names = {"Tony", "Jim"}; @DataPoints public  staticint[] ageValue1 = {10, 20};

Shows the use examples of four JUnit runtimes, with support for this four runner, and basically most of the test requirements can be solved. Of course, JUnit offers much more than that. In addition, we can also use JUNIT4 to provide rule/assume/assert and so on.

Where rule can be used to specify test rules for unit tests, the available rule is shown below:

Verifier: Verifies the correctness of test execution results.

Errorcollector: Collects error messages that occur in test methods, tests are not interrupted, and marks fail if errors occur.

ExpectedException: Provides flexible exception verification capabilities.

Timeout: The rule used to test timeouts.

Externalresource: External resource management.

Temporaryfolder: Create and delete new temporary directories before and after JUnit tests are executed.

Testwatcher: Monitor the various stages of the test method life cycle.

TestName: Provides the ability to obtain a test name during the execution of a test method.

In addition, assume said that the hypothesis, but it is actually treated with no method of the parameters of the legitimacy check, if the calibration is not qualified to throw the exception directly, and do not perform the test. This is similar to the predictions in guava. Assume provides the following validation rules:

Assumetrue/assumefalse, Assumenotnull, Assumethat, assumenoexception

For example: (You can also see in the following code that you should use @theory annotations to use parameters)

@Theorypublicvoidint age) {        assume.assumetrue (age > 0);  If the parameter is age<=0, the assumptionviolatedexception exception        System.out.println (String.Format ("%s" Name is%s) is thrown. ", name, age));

Assert is a junit-provided assertion, unlike assume, where an assert is a checksum of a test result, and it provides the following inspection rules:

Asserttrue, Assertfalse: True, false for the result.

Assertthat: Use Matcher to do a custom check.

Assertequals, Assertnotequals: Determines whether two objects are equal.

Assertnull, Assertnotnull: Determines whether the object is empty.

Assertsame: Determines whether two objects are the same, unlike equals, which is judged using "= =".

Assertarrayequals: Determines whether two arrays are equal.

Advanced usage of JUNIT4 unit testing

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.