有很多方法可以将Cucumber与Spring Boot集成在一起。但我也找不到如何与Mockito这样做。如果我使用Cucumber运行器并使用ContextConfiguration和SpringBootTest注释steps文件,则容器会注入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
}
答案 0 :(得分:0)
Runner:
List<Integer> res = new ArrayList<>();
for (int i = bucket.length - 1; i >= 0; i--) {
if (bucket[i] == null) {
continue;
}
res.addAll(bucket[i]);
if (res.size() >= k)
break;
}
在这里,我们将使用@SpringBootTest和@RunWith(SpringRunner.class)创建一个类,以开始将bean加载到spring上下文中。现在我们将在这里嘲笑那些四季豆
@CucumberOptions(plugin = {"pretty"},
glue = {"com.cucumber.test"},
features = "src/test/java")
public class CucumberTest {
}
现在,我们需要将带注释的SpringBootTest测试类扩展到CucumberSteps类,然后在此处自动装配模拟bean,将获得模拟bean(Mockedbean)的实例。我们可以进行自动装配,也可以获取其他Spring Boot bean的实例(TestBean)
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTest {
@MockBean
private Mockedbean mockedbean;
}
}