Spring @MockBean 未注入 Cucumber

Bog*_*ciu 6 java spring cucumber mockito spring-boot

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

@Service
public class SchedulerService {

  @Inject
  private AgentRestClient agentRestClient;

  public String updateStatus(String uuid) {
    String status = agentRestClient.get(uuid);
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

为了测试这个服务,我正在使用 Cucumber,同时我试图模拟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...
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行任何 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)
Run Code Online (Sandbox Code Playgroud)

为了达到这一点,我遵循了以下 2 个资源,但仍然没有运气让它工作:

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

那么你能告诉我我错过或误解了哪些 Cucumber 或 Spring 配置吗?

谢谢,博格丹

wan*_*ngf 5

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

}
Run Code Online (Sandbox Code Playgroud)


Bog*_*ciu 3

好的,所以我发现@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...
}
Run Code Online (Sandbox Code Playgroud)

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

我希望这有帮助。