【发布时间】:2022-01-23 22:10:40
【问题描述】:
我正在尝试使用 @WebMvcTest 并使用 @MockBean 模拟我的服务,并注入要模拟的 restTemplate var (junit5)。
如何在服务模拟中使用 bean 配置以及如何在模拟服务中模拟 restTemplate var?
我需要从已经创建配置的服务中限定restTemplate。
Bean配置类
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
服务类
@Service
public class MyService {
// restTemplate is coming null on tests
@Autowired
private RestTemplate restTemplate;
public ResponseEntity<Object> useRestTemplate() {
return restTemplate.exchange(
"url",
HttpMethod.POST,
new HttpEntity<>("..."),
Object.class);
}
}
测试类
@WebMvcTest(controllers = MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MyService myService;
@MockBean
private RestTemplate restTemplate;
@Test
void test() throws Exception{
when(gatewayRestService.useRestTemplate()).thenCallRealMethod();
when(
restTemplate.exchange(
anySring(),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(Object.class)
)
).thenReturn(ResponseEntity.ok().body("..."));
mockMvc.perform(
post("/path")
.content("...")
.header("Content-Type", "application/json")
)
.andExpect(status().isOk() );
}
}
我尝试在MyControllerTest 上使用@Import(RestTemplateConfig.class) 但没有成功,restTemplate 在服务测试中继续为空
【问题讨论】:
标签: java spring-boot junit5 mockmvc