您的位置:首页 > 教育 > 锐评 > 辽宁政府招标网_制作手工作品_竞价托管推广多少钱_网络推广的优势

辽宁政府招标网_制作手工作品_竞价托管推广多少钱_网络推广的优势

2025/2/23 19:17:25 来源:https://blog.csdn.net/daqi1983/article/details/145631058  浏览:    关键词:辽宁政府招标网_制作手工作品_竞价托管推广多少钱_网络推广的优势
辽宁政府招标网_制作手工作品_竞价托管推广多少钱_网络推广的优势

在pom文件中添加测试依赖

 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

复制粘贴自动创建的单元测试类

文件名改为HelloControllerTests

编写单元测试方法

@Autowired
private HelloController helloController;@Test
public void testHello() {String hello = helloController.hello();System.out.println(hello);Assert.isTrue("hello Spring Boot".equals(helloController.hello()), "helloController.hello()的返回值必须等于hello Spring Boot");}

使用MockMvc来做单元测试 

import org.junit.jupiter.api.Test;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;  
import org.springframework.test.web.servlet.MockMvc;import cn.zptc.autoapp.demos.web.HelloController;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;  @WebMvcTest(HelloController.class)  
public class HelloControllerTest2 {  @Autowired  private MockMvc mockMvc;  @Test  public void whenGetGreeting_thenCorrectResponse() throws Exception {  mockMvc.perform(get("/hello"))  .andExpect(status().isOk())  .andExpect(content().string("Hello, World!"));  }  
}

这些测试通常运行得很快,因为它们不依赖于整个Spring应用程序的上下文启动。

它们专注于测试Controller的逻辑,而不需要启动整个服务器或数据库连接

启动tomcat来做单元测试

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;import static org.assertj.core.api.Assertions.assertThat;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerTest {@LocalServerPortprivate int port;@Autowiredprivate TestRestTemplate restTemplate;@Testpublic void testSayHello() {String url = "http://localhost:" + port + "/hello";String response = restTemplate.getForObject(url, String.class);assertThat(response).isEqualTo("Hello, World!");}
}

执行测试方法

光标定位到方法名称上,右键--》Run As --》JUnit Test。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com