• 发表于 6个月前
• 阅读 8
• 收藏 0
• 评论 0

• 参数测试
• 异常测试
• 超时测试
• 灵活固件
• 忽略测试
• 对测试进行逻辑分组

# 参数测试

``````public class Fibonacci {
public static int compute(int n) {
int result = 0;

if (n <= 1) {
result = n;
} else {
result = compute(n - 1) + compute(n - 2);
}

return result;
}
}
``````

``````@RunWith(Parameterized.class)
public class FibonacciTest {

@Parameters
public static Collection<Object[]> data() {
/* 数组第一个 为 参数， 第二个为 期望结果 */
return Arrays.asList(new Object[][] {{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}});
}

private int fInput;

private int fExpected;

public FibonacciTest(int input, int expected) {
fInput = input;
fExpected = expected;
}

@Test
public void test() {
Assert.assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
``````

``````@RunWith(Parameterized.class)
public class FibonacciTest2 {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}});
}

@Parameter // first data value (0) is default
public /* NOT private */ int fInput; // 数组第一个参数为输入参数

@Parameter(1)
public /* NOT private */ int fExpected; // 数组第一个参数为 预期参数

@Test
public void test() {
Assert.assertEquals(fExpected, Fibonacci.compute(fInput));
}
}
``````

# 异常测试

``````new ArrayList<Object>().get(0);
``````

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

``````public class TestExyRule {
@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); // execution will never get past this line
}
}
``````

``````import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class TestExy {
@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldThrow() {
TestThing testThing = new TestThing();
thrown.expect(UnsupportedOperationException.class);
thrown.expectMessage(startsWith("some Message"));
testThing.chuck();
}

private class TestThing {
public void chuck() {
throw new UnsupportedOperationException("some Message");
}
}
}
``````

https://github.com/junit-team/junit4/wiki/Exception-testing

# 超时测试

``````@Test(timeout =1000)
public void testMethod() {
for(;;){}
}
``````

# 灵活固件

https://github.com/junit-team/junit4/wiki/Aggregating-tests-in-suites

# 逻辑分组测试

https://github.com/junit-team/junit4/wiki/Categories

×