首个单元测试

   单元测试是程序员编写的一段代码,用于执行另外一段代码的行为是否和预期的一致。

  环境配置

     使用的maven导入所需要的包,笔者使用的Junit4、Junit5、PowerMock、Mockito包

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>

被测试的类
public class Largest {
public static int largest(int [ ] list){
int index = 0;
int max = 0;
for (index = 0; index < list.length-1; index++) {
if (list[index] > max) {
max = list[index];
}
}
return max;
}
}

测试类

该类是从循环中取出最大值,对于给定的一个list,显然元素的位置对该方法的结果不会产生影响,马上就会想到如下的测试:
[7,8,9]
[8,7,9]
[9,7,8]
如果list中有两个相等,会出现什么情况呢
[7,9,8,9]
如果list中只有一个元素呢
[1] - > 1
如果list中含有负数呢
[-9,-8,-7]
单元测试代码如下:
import org.junit.jupiter.api.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.*;

public class LargestTest {

@Test
void largest() {
assertEquals(9,Largest.largest(new int[]{7,8,9}));
assertEquals(9,Largest.largest(new int[]{9,8,7}));
assertEquals(9,Largest.largest(new int[]{7,9,8}));
assertEquals(1,Largest.largest(new int[]{1}));
assertEquals(-7,Largest.largest(new int[]{-7,-8,-9}));
}
}

运行该测试类报错
 

 实际结果与我们期望的结果不相等,发现是list.length-1写错了,应该是list.length。

修改完代码后继续运行:

 

这个时候期望的是-7,但实际得到的结果是0,通过检查代码发现最大值写的有问题,应该是最小值,马上更改为Integer.MIN_VALUE,在运行

 

 终于运行成功了,好开心。

再想想还有没有设计上需要改动,如果我们传递的是一个空数组给程序时,是不是需要检查是否会抛出一个异常。

修改被测试的代码如下:

public class Largest {

public static int largest(int [ ] list){
int index = 0;
int max = Integer.MIN_VALUE;
if(list.length == 0){
throw new RuntimeException("Empty list");
}
for (index = 0; index < list.length; index++) {
if (list[index] > max) {
max = list[index];
}
}
return max;
}
}

添加测试代码:

import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.*;

public class LargestTest {

@Test
void largest() {
Throwable exception = assertThrows(RuntimeException.class,() -> {
Largest.largest(new int[]{});
});
assertEquals("Empty list",exception.getMessage());
assertEquals(9,Largest.largest(new int[]{7,8,9}));
assertEquals(9,Largest.largest(new int[]{9,8,7}));
assertEquals(9,Largest.largest(new int[]{7,9,8}));
assertEquals(1,Largest.largest(new int[]{1}));
assertEquals(-7,Largest.largest(new int[]{-7,-8,-9}));
}
}
在继续运行我们的单元测试:

 

 单元测试类运行成功

 


 

           

   

    

 

posted @ 2021-08-24 01:32  雨晨漫步  阅读(50)  评论(0编辑  收藏  举报