JUnit tutorial (3)

Source: Internet
Author: User
Tags junit tutorial

Iv. instance Summary

1. parameterized Test

Sometimes, different parameter values in a test method produce different results. To test the completeness of the test, multiple parameter values are written and tested one by one, in this way, it is sometimes time-consuming and labor-consuming, so we can use parameterized tests to solve this problem. Parameterization testing is like passing in a set of "input value, expected value" to the test method to achieve one-time testing.

package test;import static org.junit.Assert.*;import java.util.Arrays;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;@RunWith(Parameterized.class)public class FibonacciTest {    @Parameters(name = "{index}: fib({0})={1}")    public static Iterable<Object[]> data() {        return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },                { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });    }    private int input;    private int expected;    public FibonacciTest(int input, int expected) {        this.input = input;        this.expected = expected;    }    @Test    public void test() {        assertEquals(expected, Fibonacci.compute(input));    }}class Fibonacci {public static int compute(int input) {int result;switch (input) {case 0:result = 0;break;case 1:case 2:result = 1;break;case 3:result = 2;break;case 4:result = 3;break;case 5:result = 5;break;case 6:result = 8;break;default:result = 0;}return result;}}

@ Parameters annotation parameter name, which is actually the name of the test method. Since a test () method completes all tests, if a group of test data has problems, how can we present the results on the JUnit results page? Therefore, using name is actually the name of the test method that distinguishes each test data. For example:

2. Packaging Test

Similarly, if a project contains many test cases, it is difficult to perform one test. Therefore, testing by packaging is all the test cases contained in the one-time test completion package.

package test;import org.junit.runner.RunWith;import org.junit.runners.Suite;@RunWith(Suite.class)@Suite.SuiteClasses({ AssertTests.class, FibonacciTest.class, JDemoTest.class })public class AllCaseTest {}

This function also requires a special runner, which needs to pass a parameter suite. class to the @ runwith annotation. At the same time, we also need another annotation @ suite. suiteclasses to indicate that this class is a packaging test class. And pass the class to be packaged as a parameter to this annotation. As for allcasetest, you can create a class name without any content. Run the allcasetest class to complete the packaging test.

3. Exception Test

Exception testing is different from general assertion testing. There are three methods, the most flexible of which is the third one, which can be used in combination with assertion.

First:

  @Test(expected= IndexOutOfBoundsException.class)   public void empty() {        new ArrayList<Object>().get(0);   }

Second:

  @Test  public void testExceptionMessage() {      try {          new ArrayList<Object>().get(0);          fail("Expected an IndexOutOfBoundsException to be thrown");      } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {          assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));      }  }

Third:

    @Rule    public ExpectedException thrown = ExpectedException.none();    @Test    public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {        List<Object> list = new ArrayList<Object>();        thrown.expect(IndexOutOfBoundsException.class);        thrown.expectMessage("Index: 0, Size: 0");        list.get(0);        Assert.assertEquals(1, list.get(0));    }

In the preceding methods, both expected and expect CT indicate the expected exception. If a method is set to a value, an exception is thrown, if you use the first method, you must write a test method for this parameter to test the exception, but cannot write it in a test method together with other parameter values. The second method solves this problem, but it is not complicated but hard to understand. The third type of violation can not only dynamically change the exception to be thrown, but also combine it with the asserted statement. Therefore, we recommend that you use this method to test the exception.

4. Limited Time Test

Sometimes, in order to prevent endless loops or method execution from being too long (or check method efficiency), you need to use a time-limited test. As the name suggests, testing fails if the specified time is exceeded. There are two writing methods.

First:

@Test(timeout=1000)public void testWithTimeout() {  ...}

Second:

public class HasGlobalTimeout {    public static String log;    @Rule    public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested    @Test    public void testInfiniteLoop1() {        log += "ran1";        for (;;) {        }    }    @Test    public void testInfiniteLoop2() {        log += "ran2";        for (;;) {        }    }}

The second method is similar to the third method for exception testing. It is also recommended.

 

So far, the summary article of JUnit has been completed. Through the system summary, we have further deepened our understanding of JUnit, hoping to help our friends who do not quite understand JUnit. If you have any good suggestions and usage, you are welcome to discuss them together.

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.