spring-helloworld

项目目录
  • src/main/resources 下的程序入口:DemotestApplication
  • src/main/resources下的配置文件:application.properties
  • src/test/下的测试接口:DemotestApplicationTests
引入Web模块

当前pom.xml中

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • spring-boot-starter:核心模块,包括自动配置支持,日志和
  • spring-boot-starter-test:测试模块,包括JUnit,Hamcrest,Mockito
  • spring-boot-starter-web:web模块

编写HelloWorld服务

创建HellController类

启动主程序,打开浏览器访问http://localhost:8080/hello,可以看到页面输出Hello World

编写单元测试用例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class DemotestApplicationTests {

    private MockMvc mvc;

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

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

}

使用MockServletContext来创建一个空的WebApplicationContext,这样我们创建的HellController就可以在@Before函数中创建并传递到MockMvcBuilders.standaloneSetup函数中。

注意引入下面的内容,让status、context、equalTo函数可用

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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。