第一个SpringBoot项目

编写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.pyr.spring.cloud.weather.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!";
}
}

编写测试用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.pyr.spring.cloud.weather.controller;

import org.junit.jupiter.api.Test;
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.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;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class helloControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
void hello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("hello World!")));
}
}

启动项目

  • idea 里面右击项目
  • build/libs下运行 Java -jar xxx
  • 项目目录下运行:gradle bootRun


第一个SpringBoot项目
http://example.com/第一个springboot项目/
作者
Panyurou
发布于
2021年12月25日
许可协议