核心——断言
断言是编写测试用例的核心实现方式,即期望值是多少,测试的结果是多少,以此来判断测试是否通过。
1. 断言核心方法
assertArrayEquals(expecteds, actuals) | 查看两个数组是否相等。 |
assertEquals(expected, actual) | 查看两个对象是否相等。类似于字符串比较使用的equals()方法 |
assertNotEquals(first, second) | 查看两个对象是否不相等。 |
assertNull(object) | 查看对象是否为空。 |
assertNotNull(object) | 查看对象是否不为空。 |
assertSame(expected, actual) | 查看两个对象的引用是否相等。类似于使用“==”比较两个对象 |
assertNotSame(unexpected, actual) | 查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象 |
assertTrue(condition) | 查看运行结果是否为true。 |
assertFalse(condition) | 查看运行结果是否为false。 |
assertThat(actual, matcher) | 查看实际值是否满足指定的条件 |
fail() | 让测试失败 |
2.在service下面创建GirlService 使用findOne 通过ID查询年龄
/** * 查询一个女生通过ID */ public Girl findOne(Integer id){ return girlRepository.findById(id).orElse(null); }
3.选中findOne 点击右键使用go to 点击Test 生成测试方法
package com.imooc.student.service; import com.imooc.student.daomian.Girl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; /** * @author GXX * @data 2018/7/6 21:35 */ @RunWith(SpringRunner.class) @SpringBootTest public class GirlServerTest { @Autowired private GirlServer girlServer; @Test public void findOne() { Girl girl = girlServer.findOne(1); //设置断言 Assert.assertEquals(new Integer(14),girl.getAge()); } }
4.控制台返回错误信息
java.lang.AssertionError:
Expected :14
Actual :25
<Click to see difference>
1.设置GirlContenterTest.java 测试类
package com.imooc.student.controller; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.Assert.*; /** * @author GXX * @data 2018/7/6 21:42 */ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class GirlContenterTest { @Autowired private MockMvc mvc; @Test public void getListGirl() throws Exception{ /**请求get post 请求. */ mvc.perform(MockMvcRequestBuilders.get("/girls")) /**获取 URL. */ .andExpect(MockMvcResultMatchers.status().isOk()) /** 返回 数据.*/ .andExpect(MockMvcResultMatchers.content().string("abc")); } }
2.控制台返回错误请求:
Expected :abc
Actual :[{"id":1,"cupSize":"66","age":25,"address":"6"}]
& 使用Maven打包项目 查询测试类错误:
mvn clean package
& 使用Maven打包项目 跳过测试类:
mvn clean package -Dmaven.test.skip=true