junit 4.11中三个新功能

junit 4.11中两个新增的功能,首先是注解中可以参数化,比如


import static org.junit.Assert.assertEquals;
 
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 ParameterizedTest {
	@Parameters(name = "Run #{index}: {0}^2={1}")
	public static Iterable<Object[]> data() {
		return Arrays.asList(new Object[][] { { 1, 1 }, { 2, 4 }, { 3, 9 },
				{ 4, 16 }, { 5, 25 } });
	}
 
	private final int input;
	private final int resultExpected;
 
	public ParameterizedTest(final int input, final int result) {
		this.input = input;
		this.resultExpected = result;
	}
 
	@Test
	public void testUserMapping() {
		Calculator calc = new Calculator();
		assertEquals(resultExpected, calc.square(input));
	}



2) 指定输出顺序
  
@FixMethodOrder(MethodSorters.JVM)
public class ExecutionOrder1Test {
    @Test
    public void bTest() {
        System.out.println("b");
    }

    @Test
    public void aTest() {
        System.out.println("a");
    }

    @Test
    public void dTest() {
        System.out.println("d");
    }

    @Test
    public void cTest() {
        System.out.println("c");
    }
}


  上面的是随机顺序,可以按照方法名进行升序降序排列
@FixMethodOrder(MethodSorters.NAME_ASCENDING)


3) TestWatcher 对成功或者失败的方法进行监听
 

import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
 
import org.junit.Rule;
import org.junit.Test;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
 
public class WatcherExampleTest {
	@Rule
	public TestWatcher watcher = new TestWatcher() {
		@Override
		protected void skipped(final AssumptionViolatedException e,
				final Description description) {
			System.out.println("method " + description.getMethodName()
					+ " was skipped because of '" + e.getMessage() + "'");
		}
	};
 
	@Test
	public void testSomething() {
		assertTrue(true);
	}
 
	@Test
	public void testIgnored() {
		assumeFalse(true); // assumption fails
	}

你可能感兴趣的:(java)