---
title: "JUnit 4 测试实例"
author: "taowayi"
date: "2012-08-09T21:53:34Z"
tags: []
categories: ["编程语言"]
slug: "junit-4"
draft: false
lastmod: "2012-08-09T21:53:34Z"
id: 1627607
url: "https://andto.iteye.com/blog/1627607"
---

JUnit 4 测试的有效性。你可以打开和关闭这个计算器，而且你可以清除这些结果。下面是其实现代码：

```
public class Calculator {
　 private static int result; //存储结果的静态变量 
　 public void add(int n) { 
　　 result = result + n; 
　 } 
　 public void substract(int n) { 
　　 result = result - 1; //错误：应该是 "result = result - n"
　 } 
　 public void multiply(int n) {} //还没实现 
　 public void divide(int n) { 
　　 result = result / n; 
　 } 
　 public void square(int n) { 
　　 result = n * n; 
　 } 
　 public void squareRoot(int n) { 
　　 for (; ;) ; //错误：无限循环 
　 } 
　 public void clear() { //清除结果 
　　 result = 0; 
　 } 
　 public void switchOn() { //打开屏幕，显示 "hello"，并报警
　　 result = 0; //实现其它的计算器功能 
　 } 
　 public void switchOff() { } //显示 "bye bye"，报警，并关闭屏幕
　 public int getResult() { 
　　 return result; 
　 } 
}
```

 

JUnit 4 测试类

 

```
import calc.Calculator;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
　 private static Calculator calculator = new Calculator(); 
　 @Before public void clearCalculator() { 
　　 calculator.clear(); 
　 } 
　 @Test public void add() { 
　　 calculator.add(1); 
　　 calculator.add(1); 
　　 assertEquals(calculator.getResult()， 2); 
　 } 
　 @Test public void subtract() { 
　　 calculator.add(10); 
　　 calculator.subtract(2); 
　　 assertEquals(calculator.getResult()， 8); 
　 } 
　 @Test public void divide() { 
　　 calculator.add(8); 
　　 calculator.divide(2); 
　　 assert calculator.getResult() == 5; 
　 } 
　 @Test(expected = ArithmeticException.class) 
　 public void divideByZero() { 
　　 calculator.divide(0); 
　 } 
　 @Ignore( "not ready yet")
　 @Test 
　 public void multiply() { 
　　 calculator.add(10); 
　　 calculator.multiply(10); 
　　 assertEquals(calculator.getResult()， 100); 
　 } 
} 
```