Spring @MockBean没有注入Cucumber

时间:2016-12-27 15:21:38

标签: java spring spring-boot cucumber mockito

我正在实现一个SchedulerService,它使用AgentRestClient bean从外部系统获取一些数据。它看起来像这样:

@Service
public class SchedulerService {

  @Inject
  private AgentRestClient agentRestClient;

  public String updateStatus(String uuid) {
    String status = agentRestClient.get(uuid);
    ...
  }
  ...
}

为了测试这项服务,我正在使用Cucumber,同时我正在尝试使用Spring Boot的AgentRestClient注释来模拟@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...
}

当我尝试运行任何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)

为了达到这一点,我遵循了以下两个资源,但仍然没有运气得到它的运气:

罪魁祸首似乎是Cucumber与Spring的集成,因为当我使用普通的JUnit @Test方法尝试相同的方法时,模拟按预期工作。

那么请你告诉我黄色或春天配置我错过或误解了什么?

谢谢, 波格丹

3 个答案:

答案 0 :(得分:2)

@MockBean不被忽略,bean被嘲笑但是它没有被注入,所以你可以通过@inject注入它,这对我来说很好用:

@Inject
@MockBean
private AgentRestClient agentRestClient;

答案 1 :(得分:0)

好的,所以我发现@MockBean注释被忽略了,因为我用Cucumber运行测试而不是通过Spring Boot运行它们。咄...

所以我用@MockBean替换@Mock,然后我手动将该模拟注入我的服务层。

所以现在我的测试看起来像这样:

@SpringBootTest(classes = CentralApp.class)
@ContextConfiguration
public class RefreshActiveJobsStepDefs {

  @Inject
  private SchedulerService schedulerService;

  @Mock
  private AgentRestClient agentRestClient;

  @Before
  public void setup() throws Exception {
   MockitoAnnotations.initMocks(this);
   given(agentRestClient.get(anyString())).willReturn("FINISHED");
   schedulerService.setAgentRestClient(agentRestClient);
  }
  //Skipping the actual Given-When-Then Cucumber steps...
}

正如您所看到的,我还删除了@CucumberOptions(glue=...)注释,现在我确保通过运行器传递它,对于CLI,它将使用--glue选项。

我希望这会有所帮助。

答案 2 :(得分:0)

@ 3wj的方法适合我。 在我的例子中,bean可选地注入控制器。看起来在这种情况下,@ MockBean将无法正常工作,我猜其原因是bean没有被硬引用。添加一个额外的注释@Autowired以使bean被硬引用,然后Spring将初始化bean。

@RestController
public class MyController {

    public MyController(@Autowired(required = false) IMyService myService) {
        this.myService = myService;
    }

    @GetMapping("/the/path")
    public ResponseEntity<String> getData() {
        if(this.myService==null){
            //Throw service unavaillable exception
        }
        String data = this.myService.getData();
        return new ResponseEntity<>(data, HttpStatus.OK);
    }
}


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyControllerIT {

    @Value("${local.server.port}")
    private int port;

    private RestTemplate restTemplate;

    @Autowired
    @MockBean
    private IMyService myService 

    @Test
    public void testQuery() throws Exception {
        // restTemplate to call rest API....
    }

}