java - Spring @MockBean 未注入(inject) Cucumber

标签 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 的 @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 永远不会被模拟/注入(inject)。 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 个资源,但仍然没有成功:

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

那么您能否告诉我我遗漏或误解了哪些 Cucumber 或 Spring 配置?

谢谢, 博格丹

最佳答案

@3wj 的方法对我有用。 在我的例子中,bean 可以选择性地注入(inject)到 Controller 中。看起来在这种情况下,@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....
    }

}

关于java - Spring @MockBean 未注入(inject) Cucumber,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41347764/

相关文章:

java - java中对象列表的字母数字排序

java - Android RestTemplate json反序列化

postgresql - 如何准备使用 PostgreSQL 内存替换的集成测试?

java.lang.ClassNotFoundException : org. springframework.core.io.Resource

xml - Spring Controller 无法返回 JSON

java - 授权在本地工作但不托管

java - 可选对象 spring boot - 获取对象字段

java - hibernate/jpa double OneToOne 与一个实体的双向关系

java - War文件无法在Tomcat 7上部署

java - 关于对象生命周期的问题