SpringBoot Unit Test 记录

引入dependency:

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

写一个对于新增订单的接口的test:

package cn.order.controller;

/**
 * @author kyleli
 * @ClassName OrderControllerTest
 */

import org.junit.Before;
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.http.MediaType;
import org.springframework.test.annotation.Rollback;
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 org.springframework.transaction.annotation.Transactional;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class OrderControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Before
    public void setUp() throws Exception {
        System.out.println("test starting");
        add();
        System.out.println("test ending");
    }

    @Test
    @Transactional
    @Rollback()
    public void add() throws Exception {
        String json="{\"destination\": [22.29, 114.1986], \"origin\": [22.28, 114.1911]}";
        mockMvc.perform(MockMvcRequestBuilders
                .post("/orders")
                .content(json.getBytes())
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(print());


    }

    @Test
    public void getAll() throws Exception{
        this.mockMvc.perform(MockMvcRequestBuilders
                        .get("/orders?page=1&limit=10"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(print());
    }
}

最后出来的结果是:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /orders
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"63"]
             Body = {"destination": [22.29, 114.1986], "origin": [22.28, 114.1911]}
    Session Attrs = {}

Handler:
             Type = cn.order.controller.OrderController
           Method = cn.order.controller.OrderController#addOrder(AddOrderRequestBody)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"id":5,"distance":"3487","status":"UNASSIGNED"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
test ending
Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7a1ddbf1] from current transaction
==>  Preparing: INSERT INTO `order` ( distance, status ) VALUES ( ?, ? )
==> Parameters: 3487(String), UNASSIGNED(String)
<==    Updates: 1
Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7a1ddbf1]

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /orders
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"63"]
             Body = {"destination": [22.29, 114.1986], "origin": [22.28, 114.1911]}
    Session Attrs = {}

Handler:
             Type = cn.order.controller.OrderController
           Method = cn.order.controller.OrderController#addOrder(AddOrderRequestBody)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"id":6,"distance":"3487","status":"UNASSIGNED"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7a1ddbf1]
Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7a1ddbf1]
2023-11-04 01:47:38.356  INFO 18932 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test: [DefaultTestContext@306cf3ea testClass = OrderControllerTest, testInstance = cn.order.controller.OrderControllerTest@25533bba, testMethod = add@OrderControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@2beee7ff testClass = OrderControllerTest, locations = '{}', classes = '{class cn.order.OrderApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@5136d012 key = [org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration, org.springframework.boot.test.autoconfigure.web.reactive.WebTestClientAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@46238e3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1efee8e7, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@31206beb, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@3444d69d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@4b3fa0b3, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@64d7f7e0, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@4232c52b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]

但是加入@Transactional 和@Rollback() 在方法名上面没有rollback post请求的addOrder

尝试此方法:

java - Spring-test's @Rollback doesn't rollback anything - Stack Overflow

 把@Transactional 加在类名上

package cn.order.controller;

/**
 * @author kyleli
 * @ClassName OrderControllerTest
 */

import org.junit.Before;
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.http.MediaType;
import org.springframework.test.annotation.Rollback;
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 org.springframework.transaction.annotation.Transactional;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@Transactional

public class OrderControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Before
    public void setUp() throws Exception {
        System.out.println("test starting");
        add();
        getAll();
        System.out.println("test ending");
    }

    @Test
    public void add() throws Exception {
        //Hong Kong one place to another place
        String json="{\"destination\": [22.23, 114.1986], \"origin\": [22.28, 114.1911]}";
        mockMvc.perform(MockMvcRequestBuilders
                .post("/orders")
                .content(json.getBytes())
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(print());
    }

    @Test
    public void getAll() throws Exception{
        this.mockMvc.perform(MockMvcRequestBuilders
                        .get("/orders?page=1&limit=10"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(print());
    }
}

解决了test跑完rollback的问题

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值