如何测试Spring事件监听器的条件SpEL?

时间:2019-02-07 14:56:03

标签: spring spring-boot events mockito spring-test

我有一个工作注释驱动的事件侦听器,并带有条件语句。但是,即使代码工作正常,由于无法处理SpEL条件的测试用例也无法对该条件进行单元测试。

我注意到此错误仅在Spring Boot 1.5.x版本中发生,因为2.1.x版本按预期工作。不幸的是,我需要使用1.5.x版本。

处理事件的类:

@Component
public class MyComponent {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyComponent.class);

    @EventListener(condition = "#createdEvent.awesome")
    public void handleOrderCreatedEvent(OrderCreatedEvent createdEvent) {
        LOGGER.info("Awesome event handled");
    }

}

事件类:

public class OrderCreatedEvent {

    public OrderCreatedEvent(boolean awesome) {
        this.awesome = awesome;
    }

    private boolean awesome;

    public boolean isAwesome() {
        return awesome;
    }
}

我的考试班:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyComponent.class)
public class DemoApplicationTests {

    @Autowired
    private ApplicationEventPublisher publisher;
    @MockBean
    private MyComponent myComponent;

    @Test
    public void handleOrderCreatedEvent_shouldExecute_whenAwesome() {
        OrderCreatedEvent event = new OrderCreatedEvent(true);
        publisher.publishEvent(event);
        verify(myComponent).handleOrderCreatedEvent(event);
    }
}

完整的源代码可以在这里找到:https://github.com/crazydevman/spring-event-testing

运行应用程序,一切正常。但是,在运行测试用例时,我总是收到此错误:

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'awesome' cannot be found on null

调试代码,这似乎是由于SpEL无法解释模拟的bean的方法参数名称'createdEvent',但我不知道如何解决它。

是否可以对条件事件进行单元测试?

1 个答案:

答案 0 :(得分:2)

@Component
public class MyComponent {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyComponent.class);

    @EventListener(condition = "#root.args[0].awesome")
    public void handleOrderCreatedEvent(OrderCreatedEvent createdEvent) {
        LOGGER.info("Awesome event handled");
    }

}

enter image description here