JUnit Unit Test Learning Note three

Source: Internet
Author: User

First , advanced Fixture

In the previous article we introduced two Fixture annotations, namely @Before and @After, to see if they are suitable for the following functions: one class is responsible for reading and writing large files (more than 500 megabytes), and each of his methods is manipulating the files. In other words, before invoking each method, we have to open a large file and read the contents of the file, which is definitely a time-consuming operation. If we use @Before and @After, then each test will have to read the file once, efficiency and low. What we want here is to read the file at the start of all tests, release the file after all the tests are finished, and not read the file every time. The JUnit authors clearly consider this issue, which gives @BeforeClass and @AfterClass two Fixture to help us achieve this function. As can be seen from the name, using the two Fixture labeled functions, only when the test case is initialized to execute the @BeforeClass method, when all the tests are completed, the execution @AfterClass to perform the finishing work. Note here that only one method per test class can be labeled as @BeforeClass or @AfterClass, and that the method must be public and Static.

Second, time-limited testing.

Remember the example I gave in my introductory article, the function that squared root has a Bug, is a dead loop:

public void SquareRoot (int n) {

for (;;); Bug: Dead Loop

}

If you encounter a dead loop during testing, you will never smile on your face. Therefore, for those whose logic is very complex, the loop nesting is relatively deep, there is a possibility of a dead loop, so it is necessary to take some precautions. Time-limited testing is a good solution. We set an execution time for these test functions, more than that, they will be forcibly terminated by the system, and the system will report to you the reason for the end of the function is because of the timeout, so you can find these bugs. To do this, you only need to add a parameter to the @Test callout, as follows:

@Test (timeout = 1000)

public void SquareRoot () {

Calculator.squareroot (4);

Assertequals (2, Calculator.getresult ());

}

The timeout parameter indicates the time you want to set, in milliseconds, so 1000 represents 1 seconds.

Third, Test Exception

Exception handling in JAVA is also a priority, so you will often write some functions that need to throw exceptions. So, if you think a function should throw an exception, but it's not thrown, does that count as a Bug? This is certainly a bug, and JUnit has taken this into account to help us find this bug. For example, we write the Calculator class has the division function, if the divisor is a 0, then must throw "except 0 exception". Therefore, it is necessary for us to test these. The code is as follows:

@Test (expected = ArithmeticException. Class)

public void DivideByZero () {

Calculator.divide (0);

}
如上述代码所示,我们需要使用@Test the expected attribute of the callout, pass the exception that we want to test to him, so that the JUnit framework can automatically help us detect if the exception we specified is thrown.

Four, Runner ( runner)

Have you ever thought about this question, how does the framework run your code when you submit the test code to the JUnit framework? The answer is--runner. There are many Runner in JUnit, they are responsible for invoking your test code, each Runner has its own special features, and you need to choose different Runner to run your test code as needed. Perhaps you will find it strange that we have written so many tests before, and have not explicitly specified a Runner ah? This is because there is a default Runner in JUnit, and if you do not specify it, the system automatically uses the default Runner to run your code. In other words, the following two paragraphs of code mean exactly the same:

Import Org.junit.internal.runners.TestClassRunner;

Import Org.junit.runner.RunWith;



The system default Testclassrunner is used, exactly as in the following code

public class Calculatortest {

...

}

@RunWith (Testclassrunner. Class)

public class Calculatortest {

...

}

As you can see from the above example, to specify a Runner, you need to use a @RunWith callout and pass the Runner you specify as a parameter to it. Another thing to note is that the @RunWith is used to modify the class, not to modify the function. All functions in this class are called by this Runner whenever a Runner is specified for a class. Finally, do not forget to include the appropriate package, the above example is very clear. Next, I'll show you the unique features of other Runner.

Five, The test of the parameter .

You may have encountered such a function, its parameters have many special values, or his parameters are divided into a number of areas. For example, a function to evaluate test scores, the return value is "good, good, general, pass, fail", so you write the test, at least to write 5 tests, the 5 is included in the situation, this is really a very troublesome thing. We also use our previous example to test the "calculate the square of a number" this function, for the moment divided into three categories: positive, 0, negative. The test code is as follows:

Import Org.junit.AfterClass;

Import Org.junit.Before;

Import Org.junit.BeforeClass;

Import Org.junit.Test;

Import static Org.junit.Assert. * ;



public class Advancedtest {



private static Calculator Calculator = new Calculator ();

@Before

public void Clearcalculator () {

Calculator.clear ();

}

@Test

public void Square1 () {

Calculator.square (2);

Assertequals (4, Calculator.getresult ());

}

@Test

public void Square2 () {

Calculator.square (0);

Assertequals (0, Calculator.getresult ());

}

@Test

public void Square3 () {

Calculator.square (-3);

Assertequals (9, Calculator.getresult ());

}
}

To simplify a similar test, JUNIT4 puts forward the concept of " parametric testing" , writing only one test function, passing in several cases as parameters, and testing them once. The code is as follows:

Import static org.junit.Assert.assertEquals;

Import Org.junit.Test;

Import Org.junit.runner.RunWith;

Import org.junit.runners.Parameterized;

Import Org.junit.runners.Parameterized.Parameters;



Import Java.util.Arrays;

Import java.util.Collection;



@RunWith (parameterized. Class)

public class Squaretest {



private static Calculator Calculator = new Calculator ();

private int param;

private int result;



@Parameters

public static Collection data () {

Return arrays.aslist (new object[][] {

{2, 4},

{0, 0},

{-3, 9},

} );

}

constructor to initialize the variable

public squaretest (int param, int result) {

this. param = param;

this. result = result;

}



@Test

public void Square () {

Calculator.square (param);

Assertequals (result, Calculator.getresult ());

}
}

Below we analyze the above code. First, you want to create a new class for this kind of test instead of sharing the same class with other tests, in which case we define a squaretest class. Then, you want to specify a runner for this class, but not the default runner, because special functions need to use special runner. @RunWith (Parameterized.class) This statement specifies a parameterizedrunner for this class. The second step is to define a class to be tested and define two variables, one for storing parameters and one for storing the expected results. Next, define a collection of test data, the data () method described above, which can be arbitrarily named, but must be decorated with @parameters annotations. The framework of this method will not explain, you just need to pay attention to the data, is a two-dimensional array, data 221 groups, each group of the two data, one is the parameter, one is the result you expect. For example, our first set of {2, 4},2 is the parameter, and 4 is the expected result. The order of the two data does not matter, who before who can. The constructor is followed by the function of initializing the two parameters previously defined. Here you have to pay attention to the order of the parameters, consistent with the order of the data set above. If the previous order is {parameter, expected result}, then the order of your constructor is also "constructor (parameter, expected result)" and vice versa. The last is to write a simple test example, and the previous introduction of the same wording, not much to say here.

Six, packaging testing.

From the previous introduction we can feel that in a project, it is impossible to write only one Test class, we will write many many test classes. But these test classes have to be executed one by one, and it's a bit of a hassle. With this in mind, JUnit provides us with the ability to package tests, centralize all the test classes that need to be run, and run them all at once, greatly facilitating our testing efforts. The specific code is as follows:

Import Org.junit.runner.RunWith;
Import Org.junit.runners.Suite;

@RunWith (Suite. Class)
@Suite. suiteclasses ({
Calculatortest. Class,
Squaretest. Class
} )
public class Allcalculatortests {
}

As you can see, this feature also needs to use a special Runner, so we need to pass a parameter suite.class to the @runwith callout. At the same time, we need another callout @suite.suiteclasses to show that this class is a packaged test class. We pass the class that needs to be packaged as a parameter to the callout. With these two annotations, all of the meanings have been fully expressed, so the following classes are irrelevant, with a class name, and the contents are all empty.

Comprehensive:

Annotation Learning:
@Before: Initialization method
@After: Freeing Resources
@Test: Test method, where you can test the expected exception and time-out, which contains two properties, timeout,expected
@Ignore: Ignored test methods
@BeforeClass: For all tests, execute only once and must be static void
@AfterClass: For all tests, execute only once and must be static void
A JUnit 4 unit test Case execution sequence is:
@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
The order in which each test method is called is:
@Before –> @Test –> @After

JUnit mainly has the following assertions:

Assertequals (expected, actual value) to check if two values are equal.

Assertequals (Expected object, actual object), checks whether two objects are equal, and uses the Equals () method of the object to judge.

Assertsame (Expected object, actual object), check for two pairs of http://doc.xuehai.net/with the same memory address b1c203bb23800eece776d8ddd.html image is equal, use memory address to judge, pay attention to the difference with above Assertequals method.

Assertnotsame (Expected object, actual object), checks whether two objects are not equal.

Assertnull (Object 1, Object 2) to check if an object is empty.

Assertnotnull (Object 1, Object 2) to check whether an object is not empty.

Asserttrue (Boolean condition )to check if the Boolean condition is true.

Assertfalse (Boolean condition ), check whether the Boolean condition is False assertthat and org.hamcrest.Matchers Use with:

Assertthat (T actual, matcher<t> Matcher);

where actual is the variable that needs to be tested,matcher is used to express the variable with a hamcrest match Declaration of actual expectations;

such as: Java code

1. @Test

2. public void Testadd () {

3. int result = new Test (). Add (5, 3); 5+3

4. Assertthat (result, AllOf (GreaterThan (5), LessThan (10)));//test 5+3 is greater than, etc.

At 5 and less than or equal to ten

5.}

First write so much, follow-up learning to add new things.

JUnit Unit Test Learning Note three

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.