Spring Boot Test

1. 添加Controller

新建Spring Boot工程,新建IndexController.java:

/**
 * Author: Huchx
 * Date: 2021/2/3 11:00
 */
@RestController
public class IndexController {

    @RequestMapping("/")
    public  String index(){
        return "Hello World";
    }
}

1. MockMvc

新建测试类:

/**
 * Author: Huchx
 * Date: 2021/2/3 11:01
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MockMvcIndexTest {
    @Autowired
    MockMvc mockMvc;

    @Test
    public void  index() throws Exception {
        this.mockMvc.perform(get("/")).andExpect(status().isOk())
                .andExpect(content().string("Hello World"));
    }
}

2. WebTestClient

2.1 添加依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
      <version>2.1.0.RELEASE</version>
    </dependency>

2.2. 测试类:

/**
 * Author: Huchx
 * Date: 2021/2/3 11:36
 */
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.main.web-application-type=reactive")
@AutoConfigureWebTestClient
public class WebClientIndexTest {


    @Autowired
    private WebTestClient webTestClient;
	//或者可以绑定到Controller	
	//private WebTestClient webClient = WebTestClient.bindToController(IndexController.class).build();

    @Test
    public void  index() throws Exception {
        this.webTestClient.get().uri("/").exchange().expectStatus().isOk()
                .expectBody(String.class).isEqualTo("Hello");
    }
}

3. Random Port

添加注释@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)以随机端口启动服务器。
编写测试类:


/**
 * Author: Huchx
 * Date: 2021/2/3 13:41
 */
@RunWith(SpringRunner.class)
@SpringBootTest( webEnvironment =  SpringBootTest.WebEnvironment.RANDOM_PORT,
        properties = "spring.main.web-application-type=reactive")
@AutoConfigureWebTestClient
public class RandomPortIndexTest {
    @Autowired
   private WebTestClient webTestClient;
    @Autowired
    private TestRestTemplate restTemplate;

	// @LocalServerPort 注入实际使用的端口
   @LocalServerPort
    int port;

    @Before
    public void  beforeTest(){
        System.out.println("------------实际使用的端口为:"+port+"-----------");
    }

    @Test
    public void  indexByWebClient(){
        this.webTestClient.get().uri("/").exchange().expectStatus().isOk()
                .expectBody(String.class).isEqualTo("Hello World");
    }
    @Test
    public void indexByRestTemplate(){
        String str =  this.restTemplate.getForObject("/",String.class);
        assertThat(str).isEqualTo("Hello World");
    }
}

启动服务后,端口号如图:
Tomcat Port

4. JsonTest

  1. 新建Pojo类
/**
 * Author: Huchx
 * Date: 2021/2/3 14:57
 */
public class UserPojo {
    private String name;
    private int age;

    public UserPojo() {
    }

    public UserPojo(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
  1. 新建测试类
/**
 * Author: Huchx
 * Date: 2021/2/3 14:54
 */
@RunWith(SpringRunner.class)
@JsonTest
public class JsonObjTest {

    private JacksonTester<UserPojo> json;

    @Before
    public void setup() {
        ObjectMapper objectMapper = new ObjectMapper();
        JacksonTester.initFields(this, objectMapper);
    }
    @Test
    public void testWriteJson() throws IOException {
        UserPojo object = new UserPojo("huchx",26);
        //判断是否存在字段,@.name不知道什么写法
        assertThat(json.write(object)).hasJsonPathStringValue("@.name");
        //判断值是否包含某项
        assertThat(json.write(object)).extractingJsonPathStringValue("name")
                .isEqualTo("huchx");
    }

    @Test
    public void testParseJson() throws IOException {
        String jsonStr = "{\"name\":\"huchx\",\"age\": 26}";
        assertThat(json.parseObject(jsonStr)).isEqualTo(new UserPojo("huchx",26));
        assertThat(json.parseObject(jsonStr).getName()).isEqualTo("huchx");
    }
}

5. WebMvcTest

  1. Controller
/**
 * Author: Huchx
 * Date: 2021/2/3 15:41
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("info")
    public UserPojo info(){
        return userService.detail();
    }
}

  1. Service
/**
 * Author: Huchx
 * Date: 2021/2/3 15:43
 */
@Service
public class UserService {
    public UserPojo detail(){
        return new UserPojo("huchx",26);
    }
}
  1. Test
/**
 * Author: Huchx
 * Date: 2021/2/3 15:56
 */
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class MyWebMvcTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    UserService userService;

    @Test
    public void userInfo() throws Exception {
        given(userService.detail()).willReturn(new UserPojo("huchx",25));
        MvcResult result =  this.mockMvc.perform(get("/user/info"))
                .andExpect(status().isOk())
               .andReturn();
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }
}

6 Data JPA Test

代码:https://github.com/huiyiwu/spring-boot-simple/spring-boot-data-jpa
配置好Spring Data JPA,文档参考Spring Boot Data JPA
新建测试类:

/**
 * Author: Huchx
 * Date: 2021/2/8 9:44
 */
@RunWith(SpringRunner.class)
@DataJpaTest
//引入需要使用的配置类,此处不知道为什么导入主类就可以,其他类就报异常了
@ContextConfiguration(classes = DataJpaApp.class)
//使用真实数据库进行测试
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserTest {
    @Autowired
    TestEntityManager entityManager;

    @Autowired
    UserDao userDao;

    @Before
    public void setUp(){
        MUserEntity userEntity = new MUserEntity(108,"DataJpaTest",1);
        userDao.save(userEntity);
    }

    @Test
    public void  testUser(){
        Optional<MUserEntity> mUserEntity = userDao.findById(108);
        assertNotNull(mUserEntity.get());
    }
}

7. JDBC Test

代码:https://github.com/huiyiwu/spring-boot-simple/spring-boot-jdbctemplate
关于JDBCTemplate的配置可参考Spring Boot JDBCTemplate

/**
 * Author: Huchx
 * Date: 2021/2/8 9:44
 */
@RunWith(SpringRunner.class)
@JdbcTest
@ContextConfiguration(classes = JdbcTemplateApp.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserTest {

    JdbcTemplate jdbcTemplate;
    @Before
    public void setUp(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
       dataSource.setDriverClassName("com.mysql.jdbc.Driver");
       dataSource.setUrl("jdbc:mysql://localhost:3306/spring_boot?serverTimezone=UTC");
       dataSource.setUsername("root");
       dataSource.setPassword("123456");
       this.jdbcTemplate = new JdbcTemplate(dataSource);
//        String sql = "insert into m_jdbc_template (id,name) values (null ,?)";
//        jdbcTemplate.update(sql,"JdbcTest");
    }

    @Test
    public void  testUser(){
        String sql = "Select name from m_jdbc_template where id=120";
       String userName = jdbcTemplate.queryForObject(sql,String.class);
        assertNotNull(userName);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值