SpringBoot如何进行代码测试

2025-07-18 20:29:29

1、现在的程序里面已经实现了一个最为简单的控制器程序类。package com.gwolf;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@EnableAutoConfigurationpublic class SampleController { @RequestMapping("/") @ResponseBody public String index() { return "Greetings from Spring Boot!"; } public static void main(String[] args) { SpringApplication.run(SampleController.class, args); }}

SpringBoot如何进行代码测试

3、只要进行java测试,最简单使用的就是junit,所以这个开发包一定要随测试一起导入。【springbootbase】建立一个测试程序类,现在是一个SpringBoot程序,所以需要使用注解:package com.gwolf.test;import com.gwolf.SampleController;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@SpringBootTest(classes = SampleController.class)@RunWith(SpringJUnit4ClassRunner.class)public class TestSampleController { }

SpringBoot如何进行代码测试

5、因为我们需要测试的程序是web程序,所以还需要加入注解:@WebAppConfiguration。package com.gwolf.test;import com.gwolf.SampleController;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;@SpringBootTest(classes = SampleController.class)@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfigurationpublic class TestSampleController { }

SpringBoot如何进行代码测试

7、运行单元测试类,查看测试类是否有绿色的条。

SpringBoot如何进行代码测试
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢