网上有很多方法可以将 Cucumber 与 Spring Boot 集成。但是我也找不到如何使用 Mockito 这样做。如果我使用 Cucumber runner 并使用 ContextConfiguration 和 SpringBootTest 注释步骤文件,则容器会注入(inject) Autowired 依赖项并且一切正常。问题是用 Mock、MockBean 和 InjectMocks 注释的依赖项不起作用。任何人都知道为什么它不起作用以及如何让它起作用?
编辑:可以使用 mock(Bean.class) 实例化 bean,而不是使用 Mock 注释。但是 MockBean 和 InjectMocks 等功能呢?
运行者
@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty", "html:build/cucumber_report/"},
features = "classpath:cucumber/",
glue = {"com.whatever"},
monochrome = true,
dryRun = false)
public class CucumberTest {
}
步骤
@ContextConfiguration
@SpringBootTest
public class CucumberSteps
{
@Autowired
private Bean bean;
@InjectMocks //doesnt work
private AnotherBean anotherBean;
@MockBean //doesnt work with @Mock also
MockedBean mockedBean;
@Given("^Statement$")
public void statement() throws Throwable {
MockitoAnnotations.initMocks(this); //doesnt work with or without this line
Mockito.when(mockedBean.findByField("value"))
.thenReturn(Arrays.asList());
}
//Given-When-Then
}
最佳答案
运行者:
@CucumberOptions(plugin = {"pretty"},
glue = {"com.cucumber.test"},
features = "x/y/resources")
public class CucumberTest {
}
这里我们将创建一个带有@SpringBootTest、@RunWith(SpringRunner.class) 的类来开始将bean 加载到spring 上下文中。现在将在这里模拟任何我们想要模拟的 spring bean
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTest {
@MockBean
private Mockedbean mockedbean;
}
现在,我们需要将 SpringBootTest 注解测试类扩展到 CucumberSteps 类,然后在此处 Autowiring 模拟 bean,将获得模拟 bean(Mockedbean) 的实例。我们也可以 Autowiring 并获取其他 spring boot bean 的实例(TestBean)
public class CucumberSteps extends SpringTest {
@Autowired
private Mockedbean mockedbean;
@Autowired
private TestBean testBean;
关于java - 如何整合Spring Boot、Cucumber和Mockito?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913882/