gpt4 book ai didi

spring - 当 Cucumber 与 Mockito 一起使用时,模拟对象不会被注入(inject)到服务类中

转载 作者:行者123 更新时间:2023-12-04 13:45:28 25 4
gpt4 key购买 nike

我们正在调用第三方服务,我想模拟它而不是调用它。出于某种原因,模拟 RestTemplate 不会被注入(inject),并且该类具有真正的“RestTemplate”对象。

我的 cucumber 课看起来像这样

@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 在这里不起作用?

最佳答案

它为我工作的方式是在 TestFolder 中创建一个类,然后为生成 MockRestTemplate 实例的 resttemplate 定义一个新 bean。

@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));
}

并在服务/配置类中使用
 @Autowired
RestTemplate restTemplate

关于spring - 当 Cucumber 与 Mockito 一起使用时,模拟对象不会被注入(inject)到服务类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49151485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com