<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) //会启动容器
public class DefinedPortTest {
private RestTemplate restTpl = new RestTemplate();
@Test
public void testHello() {
String result = restTpl.getForObject("http://localhost:8080/hello", String.class);
System.out.println(result);
}
}
import java.net.URI;
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.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)//会启动容器
@AutoConfigureMockMvc
public class MockEnvTest {
@Autowired
private MockMvc mvc;
@Test
public void testHello() throws Exception {
ResultActions ra = mvc.perform(MockMvcRequestBuilders.get(new URI(
"/hello")));
MvcResult result = ra.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)//不会启动容器
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void testHello() {
String result = myService.helloService();
System.out.println(result);
}
}
09-05
300
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-29
02-02
2197
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-19
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交