pom.xml文件中增加
<!--单元测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
@WebMvcTest
@SpringBootTest
@MockBean
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {
@MockBean
private RemoteService remoteService;
@Autowired
private Reverser reverser;
@Test
public void exampleTest() {
// RemoteService has been injected into the reverser bean
given(this.remoteService.someCall()).willReturn("mock");
String reverse = reverser.reverseSomeCall();
assertThat(reverse).isEqualTo("kcom");
}
}
@RunWith(SpringRunner.class)
@WebMvcTest(UserVehicleController.class)
public class MyControllerTests {
@Autowired
private MockMvc mvc;
@MockBean
private UserVehicleService userVehicleService;
@Test
public void testExample() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestServiceImpl {
@Autowired
UserService userSerice;
List<User> userList = new ArrayList<User>();
@MockBean
UserMapper userDao;
@Test
public void testGetAll(){
User user = new User();
user.setName("huaAn");
user.setId(0);
user.setAccount("9527");
BDDMockito.given(this.userDao.get(0)).willReturn(user);
org.junit.Assert.assertTrue(userSerice.getUser(0).equals(user));
}
}
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class UserJPA {
@Autowired
private UserRepository repository;
@Autowired
private TestEntityManager entityManager;
@Test
public void testExample() throws Exception {
User user = new User();
user.setAge(15);
user.setId(10);
user.setUsername("zhangsan");
this.entityManager.persist(user);
User userActual = this.repository.findByUsername("zhangsan");
assertThat(userActual.getUsername(),is("zhangsan"));
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.main.web-application-type=reactive")
public class MyWebFluxTests { ... }
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(MyTestsConfiguration.class)