【Spring boot】编写代码及测试用例入门之 Hello Spring boot _踩坑记

先贴下目录:
这里写图片描述

这是我从 start.spring.io 里下载的依赖Web的模板

// DemoApplication.java
package com.abloume.springboot.blog.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
// 这里有一个坑,没有注册扫描器,下面分析时会有说明
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
// HelloController.java
package com.abloume.springboot.blog.controller;

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

@RestController 
// 使用 @RestController 相当于 @Controller 和 @RequestBody
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello Spring boot!";
    }
}
// DemoApplicationTests
package com.abloume.springboot.blog.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Test
    public void contextLoads() {
    }

}
// HelloControllerTest
package com.abloume.springboot.blog.controller;

import com.abloume.springboot.blog.demo.DemoApplication;
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.core.IsEqual.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 Spring boot!")));
    };
};

下面贴上自己的报错图及解决方案:
这里写图片描述
解决方案:

// 这里需要指定它的启动类
@SpringBootTest(classes = DemoApplication.class)

这里写图片描述
报错404说明路径错误匹配不到,但前后路径是对应的都是 "/hello"

再仔细看 HelloController.java 发现未被使用
这里写图片描述
解决方案:需要在启动类中添加扫描注解即可
这里写图片描述
浏览器上运行看一下,Ok~
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u013451157/article/details/79981302