从一个简单的spring web应用程序开始,进行以下测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void testGreeting() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("A response: I am real ServiceA!, B response: I am real ServiceB!")));
}
}
解决方案一
使用@MockBean&@之前:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerMockBeanTest {
@MockBean
private ServiceB mockB;
@Before
public void setup() {
Mockito.when(mockB.greeting()).thenReturn("I am mock Service B!");
}
@Autowired
private MockMvc mvc;
@Test
public void testGreetingMock() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("A response: I am real ServiceA!, B response: I am mock Service B!")));
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
// activate "test" profile
@ActiveProfiles("test")
// set custom config classes (don't forget Application)
@ContextConfiguration(classes = {TestConfig.class, Application.class})
public class MyControllerTest {
// define configuration for "test" profile (inline possible)
@Profile("test")
@Configuration
static class TestConfig {
@Bean
// !
@Primary
// I had an (auto configuration) exception/clash,
// when using *same bean name*, so *not* 'serviceB()', plz.
public ServiceB mockB() {
// prepare...
ServiceB mockService = Mockito.mock(ServiceB.class);
Mockito.when(mockService.greeting()).thenReturn("I am Mock Service B!");
// and return your mock object!
return mockService;
}
}
@Autowired
private MockMvc mvc;
@Test
public void testGreetingMock() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("A response: I am real ServiceA!, B response: I am Mock Service B!")));
}
}
Complete sample at github.
我很肯定,解决方案的清单是
不完整
.