---
title: "Assert.fail()和Assert.assertFalse()"
author: "kang"
date: "2010-01-13T10:37:18Z"
tags: []
categories: ["编程语言"]
slug: "assert-fail-assert-assertfalse"
draft: false
lastmod: "2010-01-13T10:38:43Z"
id: 568991
url: "https://kang.iteye.com/blog/568991"
---

Query模块Test Case，有一系列的异常测试，选取其中之一，进行分析，主要是Assert类的用法，代码如下：

 

这段代码主要是：使用getQueryData方法时，对参数id进行检查(假如是无效或非法的id，则会抛出异常信息)

```
	@Test
	public void queryWithInvalidID() {		
		log.info("Enter GetQueryDataTest queryWithInvalidID()");
		
		try {	
			log.info("Try to getQueryData");
			dcmAPI.getQueryData(-1,  QueryType.AVG_PWR, AggregationLevel.SELF, startTime,
					oneCycleEndTime, FREQUENCY);
			log.info("getQueryData finished");
			Assert.fail("Should get exception here!");
		} catch (Exception e) {
			Assert.assertFalse("Should not get exception "
					+ e.getClass().getSimpleName() + ": " + e.getMessage(),
					Utilities.isNotExceptedException(e,
							"DcmIllegalIdException", null));
		}
		
		log.info("Exit GetQueryDataTest queryWithInvalidID()");
	}
```

 

 

名称 说明 [Assert.Fail ()](http://msdn.microsoft.com/zh-cn/library/ms243700%28VS.80%29.aspx) 在不检查任何条件的情况下使断言失败。 [Assert.Fail (String)](http://msdn.microsoft.com/zh-cn/library/ms243738%28VS.80%29.aspx) 在不检查任何条件的情况下使断言失败。显示消息。 [Assert.Fail (String, Object\[\])](http://msdn.microsoft.com/zh-cn/library/ms243776%28VS.80%29.aspx) 在不检查任何条件的情况下使断言失败。显示一则消息，并向该消息应用指定的格式。

 

 

### `fail public static void fail(java.lang.String message) Fails a test with the given message. Parameters: message - the identifying message for the AssertionError (null okay) See Also: AssertionError`

```
assertFalse
public static void assertFalse(java.lang.String message,
                               boolean condition)
Asserts that a condition is false. If it isn't it throws an AssertionError with the given message. 
 

Parameters: 
message - the identifying message for the AssertionError (null okay) 
condition - condition to be checked
```

 

 

 

以上两个方法的用法说明摘录自：[http://junit.org/apidocs/org/junit/Assert.html](http://junit.org/apidocs/org/junit/Assert.html)

 

我的简单说明：

Assert.Fail (String)：运行到该句时，直接使该断言失败，并且将括号中的String参数直接显示出来；

**assertFalse**(java.lang.String message,boolean condition)：判断参数condition是否为false，假如该参数值为true，则抛出含有参数message值的异常信息。

 

 

 

下面，我们再来分析上述测试代码：

 

1.Assert.fail("Should get exception here!");

该句的意思是说：根据上面的代码

```
dcmAPI.getQueryData(-1,  QueryType.AVG_PWR, AggregationLevel.SELF, startTime,oneCycleEndTime, FREQUENCY);
```

 参数－1，应该遇到异常，从try代码块跳出到catch代码块中了，竟然还走到了这一句，就是有问题了，所以直接使断言失败，并打印出错误信息："Should get exception here!"

 

 

2\.

```
			Assert.assertFalse("Should not get exception "
					+ e.getClass().getSimpleName() + ": " + e.getMessage(),
					Utilities.isNotExceptedException(e,
							"DcmIllegalIdException", null));
```

这段的意思： 假如此处捕获到的异常信息e不是我们期望的异常DcmIllegalIdException，则Utilities.isNotExceptedException()的返回结果是true，则会使断言失败，并且打印出异常信息“Should not get exception ”＋e，也就是说：我们在此处不应该捕获e这种异常信息的（我们应该捕获的是DcmIllegalIdException）