首先需要在pom.xml文件中导入相应的依赖:
<!-- 导入spring boot的web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 测试模块,包括Junit、Hamcrest、Mockito测试框架 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
springboot为我们提供了三种测试框架,分别是JUnit Hamcrest Mockito
Junit就是大家经常使用的单元测试,这里不做细究。
1.1 Hamcrest是什么?
Hamcrest 是一个测试的框架,它提供了大量被称为“匹配器”的方法,灵活使用这些匹配符定义的规则,程序员可以更加精确的表达自己的测试思想,指定所想设定的测试条件。
看个对比例子,前者使用Junit的 断言,后者使用 Hamcrest的断言。
@Test//Junit
public void test_with_junit_assert() {
int expected = 51;
int actual = 51;
assertEquals("failure - They are not same!", expected, actual);
}
@Test//Hamcrest
public void test_with_hamcrest_assertThat() {
int expected = 51;
int actual = 51;
assertThat("failure - They are not same!", actual,Matchers.equalTo(expected));
}
区别:
1. 参数顺序。两者的expected 和 actual 前后顺序是相反的。
2. Hamcrest 几乎总是直接使用对象。它的语法更符合函数式编程的风格。
这点很好理解了,Junit 总是获取值后再比较,因为比较的是简单的值,因此被比较的放在前面更符合习惯。
而Hamcrest 是直接对测试结果的对象进行一些更复杂的匹配。
如果觉得Hamcrest方法不够使用,还可以自定义Hamcrest匹配器,只需要实现BaseMatcher<T>
接口,自定义匹配器教程
1.2 Mockito是什么?
Mockito是mocking框架,它让你用简洁的API做测试。而且Mockito简单易学,它可读性强和验证语法简洁。
1.3 为什么需要Mock
测试驱动的开发( TDD)要求我们先写单元测试,再写实现代码。在写单元测试的过程中,我们往往会遇到要测试的类有很多依赖,这些依赖的类/对象/资源又有别的依赖,从而形成一个大的依赖树,要在单元测试的环境中完整地构建这样的依赖,是一件很困难的事情。如下图所示:
为了测试类A,我们需要Mock B类和C类(用虚拟对象来代替)如下图所示:
模拟对象的概念就是我们想要创建一个可以替代实际对象的对象.这个模拟对象要可以通过特定参数调用特定的方法,并且能返回预期结果.
使用方法:
package com.syy;
import org.hamcrest.Matchers;
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.RequestBuilder;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes= DemoApplication.class)//
//@SpringBootApplication
@AutoConfigureMockMvc
public class testMockito {
@Autowired
private MockMvc mvc; /* mvc的mock对象 */
@Test
public void testHello() {
RequestBuilder request = get("/index.jsp"); /* 定义URL,已经发起请求为get方式 */
/* 模拟发起Http请求*/
try {
System.out.println(mvc+">>>>>>");
mvc.perform(request)
.andExpect(status().isOk()) /* 比较返回码是否为200 */
.andExpect(content().string(Matchers.equalTo("{" + /* 比较返回内容 */
"\"msg\":\"HelloWorld\"," +
"\"status\":\"success\"" +
"}")));
System.out.println(">>>>>"+mvc.perform(request).toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果显示:
终于讲完了。。。