3

网上有很多方法可以将 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 {

}

脚步

@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   
}
4

1 回答 1

1

亚军:

@CucumberOptions(plugin = {"pretty"}, 
                 glue = {"com.cucumber.test"},
                 features = "x/y/resources")
public class CucumberTest { 

}

在这里,我们将使用@SpringBootTest、@RunWith(SpringRunner.class) 创建一个类,以开始将 bean 加载到 Spring 上下文中。现在将在这里模拟我们想要的任何东西

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTest {

@MockBean    
private Mockedbean mockedbean;
}

现在,我们需要将 SpringBootTest 注解的 testclass 扩展为 CucumberSteps 类,然后在这里自动装配 mocked bean,将得到 mockedbean 的实例(Mockedbean)。我们也可以进行自动装配并获取其他 Spring Boot bean 的实例(TestBean)

public class CucumberSteps extends SpringTest {

@Autowired
private Mockedbean mockedbean;

@Autowired
private TestBean testBean;

}

于 2018-11-03T08:03:49.060 回答