Junit预期异常测试用例示例

Junit是Java编程语言的单元测试框架。如果您想阅读有关junit测试的最佳实践,那么这里是一份很好的指南供您参考。

在本文中,我正在编写一个示例测试用例,期望在运行时引发异常。如果它获得预期的异常,则测试通过。如果未检测到预期的异常,则测试用例失败。

如果您希望应用程序因非常荒谬的输入而失败,这些类型的测试用例将非常有用。

package com.how2codex.test.junit;

import org.junit.Test;

public class ExpectedExceptionTest
{
	//This test case fails because it was expecting ArithmeticException
	@Test(expected = ArithmeticException.class)
	public void expectArithmeticException()
	{
		System.out.println("Everything was fine here !!");
	}

	//This test case fails because it was expecting ArithmeticException
	@Test(expected = ArithmeticException.class)
	public void expectArithmeticException2()
	{
		throw new NullPointerException();
	}

	//This test case passes because it was expecting NullPointerException
	@Test(expected = NullPointerException.class)
	public void expectNullPointerException()
	{
		//some code which throw NullPointerException in run time
		throw new NullPointerException();
	}
}

在上述3个测试用例中,前两个失败是因为他们期望ArithmeticException,而在执行测试用例时并没有得到。

第三个测试用例获得通过,因为它期望NullPointerException并被测试用例抛出。

这样,您可以编写依赖于某些异常的测试用例,以测试失败时应用程序的行为。

学习愉快!

saigon has written 1440 articles

Leave a Reply