Rog*_*eia 5 java cucumber mockito spring-boot spring-boot-test
网上有一些方法可以将 Cucumber 与 Spring Boot 集成。但我也找不到如何使用 Mockito 来做到这一点。如果我使用 Cucumber 运行程序并使用 ContextConfiguration 和 SpringBootTest 注释步骤文件,则容器会注入 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 {
}
Run Code Online (Sandbox Code Playgroud)
脚步
@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
}
Run Code Online (Sandbox Code Playgroud)
跑步者:
@CucumberOptions(plugin = {"pretty"},
glue = {"com.cucumber.test"},
features = "x/y/resources")
public class CucumberTest {
}
Run Code Online (Sandbox Code Playgroud)
这里我们将使用@SpringBootTest、@RunWith(SpringRunner.class)创建一个类来开始将bean加载到spring上下文中。现在将嘲笑春豆,无论我们想在这里做什么
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTest {
@MockBean
private Mockedbean mockedbean;
}
Run Code Online (Sandbox Code Playgroud)
现在,我们需要将SpringBootTest注释的测试类扩展为CucumberSteps类,然后在这里自动装配模拟bean,将获得模拟bean(Mockedbean)的实例。我们还可以进行自动装配并获取其他 Spring Boot bean 的实例(TestBean)
public class CucumberSteps extends SpringTest {
@Autowired
private Mockedbean mockedbean;
@Autowired
private TestBean testBean;
Run Code Online (Sandbox Code Playgroud)
}
归档时间: |
|
查看次数: |
5683 次 |
最近记录: |