测试一个简单方法

开发工具:idea

版本管理:maven

pom.xml:

1 <dependencies>
2     <dependency>
3       <groupId>junit</groupId>
4       <artifactId>junit</artifactId>
5       <version>4.12</version>
6       <scope>compile</scope>
7     </dependency>
8   </dependencies>
Largest.java
 1 package com.lenovo.unit2;
 2 
 3 /**
 4  * 寻找最大数
 5  */
 6 public class Largest {
 7 
 8     public static int largest(int[] list){
 9         int index = 0;
10         int max=Integer.MIN_VALUE;
11         for (index = 0;index < list.length; index++){
12             if(list[index] > max){
13                 max = list[index];
14             }
15         }
16         return max;
17     }
18 }
TestLargest.java
 1 package com.lenovo.unit2;
 2 import junit.framework.*;
 3 
 4 /**
 5  * 输入import junit.framework.*;查看是否能正常编译,如果可以,说明已经正确引入junit jar包
 6  * 测试Largest的寻找最大数函数
 7  * 测试类需要继承TestCase基类
 8  */
 9 public class TestLargest extends TestCase {
10 
11     public TestLargest(String name){
12         super(name);
13     }
14 
15     //测试不同顺序是否触发函数错误
16     public void testSimple(){
17         //断言,第一个参数是期望值,第二个参数是被测试函数的输入参数
18         assertEquals(9,Largest.largest(new int[]{7,8,9}));
19         assertEquals(9,Largest.largest(new int[]{9,8,7}));
20         assertEquals(9,Largest.largest(new int[]{7,9,8}));
21     }
22 
23     //测试重复数据是否触发函数错误
24     public void testRepeatNum(){
25         assertEquals(9,Largest.largest(new int[]{7,9,8,9}));
26     }
27 
28     //测试list一个元素
29     public void testOne(){
30         assertEquals(1,Largest.largest(new int[]{1}));
31     }
32 
33     //测试list中含有负值元素
34     public void testNegative(){
35         assertEquals(-7,Largest.largest(new int[]{-9,-8,-7}));
36     }
37 
38     //针对list为空情况
39     public void testEmpty(){
40         try {
41             Largest.largest(new int[]{});
42             fail("Should have thrown an exception!");
43         }catch (RuntimeException e){
44             assertTrue(true);
45         }
46     }
47 }

 

posted @ 2022-03-09 17:05  永远的希望  阅读(49)  评论(0编辑  收藏  举报