第一個SpringBoot測試實例

1.SpringBoot項目構建:http://start-spring.io   自動化構建SpringBoot項目,保存在本地並解壓java

2.安裝gradle並配置gradle環境web

3.配置阿里雲maven倉庫:修改gradle.build 裏面額maven倉庫,改成:maven{  url 'http://maven.aliyun.com/nexus/content/groups/public'  }spring

4.構建項目,進入解壓後的項目路徑下,打開控制檯執行如下命令:cmd -> cd E:/hello ->E:  ->  gradle build  ->java -jar build/libs/xxxxx.jarapp

5.導入開發工具,進行測試,測試代碼以下:maven

在main目錄下,新建HelloController類:工具

package com.waylau.spring.boot.blog.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World!";
    }
}

在test下,新建HelloControllerTest類:開發工具

package com.waylau.spring.boot.blog.contrller;

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.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Test
    public void testHello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World!")));
    }

}
相關文章
相關標籤/搜索