iis7 网站无法显示该页面,社交网站建设,门户网站制作企业,建设维护网站运营方案目录
1、单元测试#xff08;非 Web 上下文#xff09;
1.1、引入依赖
1.2 编写单元测试类(示例代码)
2、Spring MVC 控制器测试
2.1、创建控制器及映射方法
2.2 编写控制器测试类 Spring Boot 提供了强大的单元测试和集成测试支持#xff0c;以简化基于 Spring 的应用…目录
1、单元测试非 Web 上下文
1.1、引入依赖
1.2 编写单元测试类(示例代码)
2、Spring MVC 控制器测试
2.1、创建控制器及映射方法
2.2 编写控制器测试类 Spring Boot 提供了强大的单元测试和集成测试支持以简化基于 Spring 的应用程序的测试。下面分别使用 Spring Boot 进行单元测试和 Web 控制器MVC测试。
1、单元测试非 Web 上下文
1.1 引入依赖
dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency
/dependencies
1.2 编写单元测试类(示例代码)
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;RunWith(SpringRunner.class)
SpringBootTest
public class UserServiceTest {// 业务服务类ServiceAutowiredprivate UserService userService; Testpublic void testFindUser() {User user userService.findUserById(1L);// 断言检查user对象是否正确assertNotNull(user);assertEquals(用户名, user.getName());}
}
2、Spring MVC 控制器测试
针对 Spring MVC 控制器Spring Boot 提供了 MockMvc 测试工具来模拟 HTTP 请求并验证响应。
2.1 创建控制器及映射方法
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; RestController
public class ExampleController { GetMapping(/hello) public String hello() { return Hello, World!; }
}
2.2 编写控制器测试类
package com.example.demo.controller; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.hamcrest.Matchers.equalTo; WebMvcTest(ExampleController.class)
public class ExampleControllerTest { Autowired private MockMvc mockMvc; Test public void testHello() throws Exception { MvcResult mvcResult mockMvc.perform(get(/hello)) .andExpect(status().isOk()) .andExpect(content().string(equalTo(Hello, World!))) .andReturn(); String contentAsString mvcResult.getResponse().getContentAsString(); System.out.println(contentAsString); // 输出响应内容便于调试 }
} 在这个测试类中我们使用了 WebMvcTest 注解它告诉 Spring Test 加载 Spring MVC 的基础配置但是不会加载整个应用上下文因此它更适合于测试控制器。Autowired 注解用于自动注入 MockMvc 实例它提供了模拟 HTTP 请求并验证响应的功能。 在 testHello 方法中我们使用 mockMvc.perform 方法发送一个 GET 请求到 /hello 路径并使用 andExpect 方法链来验证响应的状态码和内容。如果测试失败andExpect 方法会抛出异常。 注意 在实际项目中你可能还需要编写其他类型的测试如集成测试、服务层测试、数据访问层测试等并可能需要配置不同的测试切片例如 DataJpaTest 用于数据访问层测试。 在编写测试时请确保该测试是可重复的、独立的并且尽可能地覆盖所有重要的业务逻辑场景。良好的测试实践有助于提高代码质量并减少在生产环境中出现问题的风险。 后续有时间再继续更新集成测试、服务层测试、数据访问层测试等。