Spring boot(十二):Spring boot 如何测试、打包、部署

本文详细介绍SpringBoot项目中单元测试与集成测试的方法。通过添加spring-boot-starter-test依赖,结合@RunWith和@SpringBootTest注解,实现Controller层的MockMvc测试。同时,介绍热部署配置,便于集成测试中的代码调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

博文引用:springboot(十二):springboot如何测试打包部署

开发阶段


单元测试

Spring boot对单元测试的支持已经很完善了。

1 在pom包中添加Spring-boot-starter-test包引用

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

2 开发测试类

头部添加:@RunWith(SpringRunner.class)@SpringBootTest注解,在测试方法上添加 测试方法@Test即可。

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

	@Test
	public void hello() {
		System.out.println("hello world");
	}
}

实际使用中,可以按照项目的正常使用注入dao层或是service层代码进行测试验证,spring-boot-starter-test提供很多基础用法,更难得的是增加了对Controller层测试的支持。

//简单验证结果集是否正确
Assert.assertEquals(3, userMapper.getAll().size());

//验证结果集,提示
Assert.assertTrue("错误,正确的返回值为200", status == 200); 
Assert.assertFalse("错误,正确的返回值为200", status != 200);

引入MockMvc支持对Controller层的测试,简单实例:

public class HelloControlerTests {
    private MockMvc mvc;

    //初始化执行
    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    //验证controller是否正常响应并打印返回结果
    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
    
    //验证controller是否正常响应并判断返回结果是否正确
    @Test
    public void testHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }
}

单元测试时验证你代码的第一道屏障,要养成每写一部分代码就进行单元测试的习惯,不要等到全部集成后进行测试,集成后因为更关注整体运行效果,很容易遗漏掉底层的bug。

集成测试

整体开发完成之后进入集成测试,spring boot 项目的启动入口在Application类中,直接运行run方法就可以启动项目,但是在调试的过程中我们肯定需要不断的去调试代码,spring boot 给出了对热部署的支持,很方便的在web项目中调试。

pom需要添加以下配置:

 <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
	</plugins>
</build>

添加以上配置后,项目就支持了热部署,非常方便集成测试。

投产上线


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值