天天看點

IDEA配置springboot

以2020.3.1為例

選擇spring initializr->next

IDEA配置springboot

java version選擇8

前面的Artifact可以随便起名

然後next

IDEA配置springboot

選擇web->spring web

其他的可以考慮不選,其實就算都不選,一會也可以在maven的pom.xml配置

然後next

IDEA配置springboot

直接Finish

IDEA配置springboot

在src/main/java/com.example.demo下建一個類

IDEA配置springboot
package com.example.demo;

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

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String index() {
        return "測試";
    }

}
           

修改test/java/com.example.demo下的類 

IDEA配置springboot

記住這個accept(MediaType.APPLICATION_JSON_UTF8)

如果這個沒寫,而且你傳回中文的話,很有可能測試過不了

package com.example.demo;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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 org.springframework.test.web.servlet.setup.MockMvcBuilders;

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
public class DemoApplicationTests {
    private MockMvc mvc;

    public DemoApplicationTests() {
    }

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("測試")));
    }

}
           

 然後會有紅的

然後點一下Test,alt+enter,add maven dependency ,選org.junit那個(第二個)

IDEA配置springboot

然後點一下這個開始按鈕,應該會顯示測試通過 

IDEA配置springboot

然後這個選擇最底下那個Application,然後右上角,運作

IDEA配置springboot

底下控制台會輸出這些 

IDEA配置springboot

打開浏覽器,輸出http://localhost:8080/hello

可以看到輸出測試

IDEA配置springboot