单元测试验证单个类的行为,集成测试验证多个类的组合行为。单元测试使用 junit 和 mockito 框架,集成测试使用 testng 和 spring boot 测试模块。实战案例展示了在 spring boot 应用程序中使用 mockmvc 进行单元测试,以及使用独立设置的 mockmvc 进行集成测试。
单元测试和集成测试:Java 框架的指南
在 Java 开发中,单元测试和集成测试对于确保代码质量和可靠性至关重要。本文将探讨在 Java 框架中执行这两种类型的测试的方法和技巧。
单元测试
单元测试验证单个 Java 类的行为,而无需与其他类或组件交互。对于获取代码的基本功能和创建更稳定的应用程序非常有帮助。
方法
集成测试
集成测试验证多个 Java 类的组合行为,通常包括数据库或其他外部资源的交互。这有助于检测组件集成中的错误并确保应用程序按预期工作。
方法
实战案例
考虑一个 Spring Boot 应用程序,其中包含一个 CustomerController 类和一个 CustomerService 类。
单元测试 CustomerController
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) @WebMvcTest(CustomerController.class) public class CustomerControllerTest { @Autowired private MockMvc mockMvc; @Test public void testCreateCustomer() throws Exception { // 模拟请求 MvcResult result = mockMvc.perform(post("/customers") .contentType(MediaType.APPLICATION_JSON) .content("{ \"name\": \"John Doe\" }")) .andReturn(); // 断言响应 assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus()); } }
集成测试 CustomerService 和 CustomerController
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 org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerIntegrationTest {
@Autowired
private CustomerService customerService;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(new CustomerController(customerService))
.build();
}
@Test
public void testCreateCustomer() throws Exception {
// 模拟请求
MvcResult result = mockMvc.perform(post("/customers")
.contentType(MediaType.APPLICATION_JSON)
.content("{ \"name\": \"John Doe\" }"))
.andReturn();
// 断言响应
assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
}
}