我正在實現一個SchedulerService
,它使用一個AgentRestClient
bean從外部系統獲取一些數據。它看起來是這樣的:Spring @MockBean沒有注入黃瓜
@Service
public class SchedulerService {
@Inject
private AgentRestClient agentRestClient;
public String updateStatus(String uuid) {
String status = agentRestClient.get(uuid);
...
}
...
}
爲了測試這項服務,我使用的是黃瓜,而在同一時間我試圖嘲弄的AgentRestClient
使用Spring Boot的@MockBean
標註的行爲,具體如下:
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...
}
當我嘗試運行任何黃瓜場景時,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
罪魁禍首似乎是黃瓜集成到Spring中,因爲當我用普通的JUnit @Test
方法,嘲笑按預期工作。
那麼你能告訴我什麼黃瓜或春天配置有我錯過或誤解?
感謝, 波格丹
你設法得到它的工作?我面臨同樣的問題 –
是的,請參閱下面的答案,我希望它有幫助。 –