【发布时间】:2017-05-11 21:26:44
【问题描述】:
我正在实现一个SchedulerService,它使用AgentRestClient bean 从外部系统获取一些数据。它看起来像这样:
@Service
public class SchedulerService {
@Inject
private AgentRestClient agentRestClient;
public String updateStatus(String uuid) {
String status = agentRestClient.get(uuid);
...
}
...
}
为了测试这项服务,我使用 Cucumber,同时尝试使用 Spring Boot 的 @MockBean 注释模拟 AgentRestClient 的行为,如下所示:
import cucumber.api.CucumberOptions;
import cucumber.api.java.Before;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CentralApp.class)
@CucumberOptions(glue = {"com.company.project.cucumber.stepdefs", "cucumber.api.spring"})
public class RefreshActiveJobsStepDefs {
@MockBean
private AgentRestClient agentRestClient;
@Inject
private SchedulerService schedulerService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
given(agentRestClient.get(anyString())).willReturn("FINISHED");//agentRestClient is always null here
}
//Skipping the actual Given-When-Then Cucumber steps...
}
当我尝试运行任何 Cucumber 场景时,agentRestClient 永远不会被模拟/注入。 setUp() 方法因 NPE 失败:
java.lang.NullPointerException
at com.company.project.cucumber.stepdefs.scheduler.RefreshActiveJobsStepDefs.setUp(RefreshActiveJobsStepDefs.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:37)
at cucumber.runtime.Timeout.timeout(Timeout.java:13)
at cucumber.runtime.Utils.invoke(Utils.java:31)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:223)
at cucumber.runtime.Runtime.runHooks(Runtime.java:211)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:201)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:121)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
为了达到这一点,我遵循了以下 2 个资源,但仍然没有成功:
- https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4
- http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html
罪魁祸首似乎是将 Cucumber 集成到 Spring 中,因为当我使用普通的 JUnit @Test 方法尝试相同的方法时,模拟按预期工作。
那么你能告诉我我错过或误解了哪些 Cucumber 或 Spring 配置吗?
谢谢, 波格丹
【问题讨论】:
-
你设法让它工作了吗?我也面临同样的问题
-
是的,请看下面我的回答,希望对您有所帮助。
标签: java spring spring-boot cucumber mockito