我们正在调用第三方服务,我想嘲笑而不是打电话。出于某种原因,模拟RestTemplate不会被注入,并且该类具有真正的“RestTemplate”对象。
我的黄瓜课看起来像这样
@RunWith(Cucumber.class)
@CucumberOptions(plugin = { "pretty", "html:build/cucumber",
"junit:build/cucumber/junit-report.xml" },
features = "src/test/resources/feature",
tags = { "@FunctionalTest","@In-Progress", "~@TO-DO" },
glue= "com.arrow.myarrow.service.order.bdd.stepDef")
public class CucumberTest {
}
,StepDefinition看起来像这样
@ContextConfiguration(loader = SpringBootContextLoader.class, classes =
OrderServiceBoot.class)
@WebAppConfiguration
@SpringBootTest
public class BaseStepDefinition {
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
@Rule public MockitoRule rule = MockitoJUnit.rule();
RestTemplate restTemplate = mock(RestTemplate.class);
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
//Telling rest template what to do
when(restTemplate.exchange(Mockito.anyString(), Mockito.
<HttpMethod>any(), Mockito.<HttpEntity<?>>any(), Mockito.
<Class<UserProfile>>any()))
.thenReturn(new ResponseEntity<>(userProfile,
HttpStatus.OK));
}
这是我的服务类看起来像
@Autowired
RestTemplate restTemplate;
public UserProfile getUserProfile(OAuth2Authentication auth){
ResponseEntity<UserProfile> response
=restTemplate.exchange("http://localhost:8084/api/v1.0/user/profile", HttpMethod.GET,new HttpEntity<>(new HttpHeaders()),UserProfile.class);
return response.getBody();
}
在服务类中,RestTemplate restTemplate未被模拟,它包含真实对象,因此它试图调用不适合的实际服务。
有谁知道为什么Mocking不在这里工作?
答案 0 :(得分:0)
它对我有用的方法是在TestFolder中创建一个类,然后为resttemplate定义一个新的bean,生成MockRestTemplate实例。
@Configuration
@Profile("local")
public class CucumberMockConfig {
@Bean
@Primary
public RestTemplate getRestRemplate() {
return mock(RestTemplate.class);
}
}
在测试类中使用(不要使用@Mock或Mock(restTemplate),因为你不想要一个新对象)
@Autowired
RestTemplate restTemplate
@Before
public void setup() throws JsonProcessingException {
UserProfile userProfile = new UserProfile();
userProfile.setCompany("myCompany");
when(restTemplate.exchange(Mockito.endsWith("/profile"),
Mockito.<HttpMethod>eq(HttpMethod.GET),
Mockito.<HttpEntity<?>>any(),
Mockito.eq(UserProfile.class)))
.thenReturn(ResponseEntity.ok().body(userProfile));
}
并在service / config类中使用
@Autowired
RestTemplate restTemplate