简体   繁体   中英

Groovy Spock: How do you pass in new Exception into when method without throwing error right away

I am trying to test a kafka error handler that takes in an Exception but as soon as I declare it in spock it actually throws it.

def 'test example'() {
    when:
    service.emitError(new Exception('test exception'))

    then:
    // do some tests
}

I have tried declaring it in a wrapped java class and running that in main will NOT throw an error but if I pull it into spock it will process it incorrectly.

I am trying to see if I am doing it wrong or if I can't test this with spock.

With help from Jeff I realized that it was an error on mock kafka template. When you have to pass an exception into a mock (not sure if it is just KafkaTemplate specific) and the expected mock fails something bubbles up and my try catch caught that instead. I recognize I should have posted the original code - and will in the future. This is testing on pre-refactored code that didn't have tests (not TTD)

I was missing .key('key') which was failing it.

Emitter

public class KafkaErrorNotificationEmitter {
    private final KafkaTemplate<String, TopicMessageData> kafkaTemplate;
    private final ObjectMapper objectMapper;
    private final TemporalConfig.TimeKeeper timeKeeper;
    private final String internalErrorTopic;

    public KafkaErrorNotificationEmitter(
        KafkaTemplate<String, TopicMessageData> kafkaTemplate,
        ObjectMapper objectMapper,
        TemporalConfig.TimeKeeper timeKeeper,
        @Value("${kafka.error.topic}") String internalErrorTopic
    ) {
        this.kafkaTemplate = kafkaTemplate;
        this.objectMapper = objectMapper;
        this.timeKeeper = timeKeeper;
        this.internalErrorTopic = internalErrorTopic;
    }

    public void emitError(@Nullable KesMessageProperties kesMessageProperties, Exception ex) {
        assert kesMessageProperties != null;
        String entityName = kesMessageProperties.getEntityName();

        log.warn("Failed message ({}). Sending to KES.", entityName, ex);

        String key = kesMessageProperties.getMessage().getKey();

        try {
            TopicMessageData errorMessage =
                TopicMessageData
                    .builder()
                    .sourceTopic(kesMessageProperties.getTopic())
                    .exceptionMessage(ex.getMessage())
                    .key(key)
                    .listenerType(kesMessageProperties.getListenerType())
                    .occurrenceTime(timeKeeper.nowZdt())
                    .payload(objectMapper.writeValueAsString(kesMessageProperties.getMessage()))
                    .build();

            sendEmitError(errorMessage);
        } catch (Exception e) {
            log.error("Failed to send error ({}) notification for {}", entityName, key, e);
        }
    }

    private void sendEmitError(final TopicMessageData topicMessageData) {
        log.debug("Sending error message for: {}", topicMessageData);
        kafkaTemplate.send(internalErrorTopic, topicMessageData);
    }

}

Test

class KafkaErrorNotificationEmitterSpec extends Specification {
    KafkaTemplate<String, TopicMessageData> kafkaTemplate = Mock()
    ObjectMapper objectMapper = new ObjectMapper()
    TemporalConfig.TimeKeeper timeKeeper = Mock()
    String internalErrorTopic = 'kes.error.test'

    def kafkaErrorNotificationEmitter = new KafkaErrorNotificationEmitter(
        kafkaTemplate,
        objectMapper,
        timeKeeper,
        internalErrorTopic
    )

    @Shared
    def errorMessage = 'Test exception'

    @Shared
    Exception exception = new Exception(errorMessage)

    def 'emitError throws uncaught NPE'() {
        setup:
        def properties = new KesMessageProperties(message: null)

        when:
        kafkaErrorNotificationEmitter.emitError(properties, exception)

        then:
        0 * _
        thrown NullPointerException
    }

    def 'emitError throws caught exception'() {
        setup:
        def properties = new KesMessageProperties(
            message: new IKafkaMessage() {
                @Override
                String getKey() {
                    return null
                }
            }
        )

        when:
        kafkaErrorNotificationEmitter.emitError(properties, exception)

        then:
        1 * timeKeeper.nowZdt() >> { throw new RuntimeException() }
        0 * _
    }

    def 'emitError success'() {
        setup:
        def listenerType = 'test-error'

        def properties = new KesMessageProperties(
            listenerType: listenerType,
            message: new IKafkaMessage() {
                @Override
                String getKey() {
                    return 'key'
                }
            }
        )

        def now = ZonedDateTime.now()

        def errorData =
            TopicMessageData
                .builder()
                .exceptionMessage(errorMessage)
                .listenerType(listenerType)
                //.key('key') // this is what was missing!!!
                .occurrenceTime(now)
                .payload('{\"key\":\"key\"}')
                .build()

        when:
        kafkaErrorNotificationEmitter.emitError(properties, exception)

        then:
        1 * timeKeeper.nowZdt() >> now
        1 * kafkaTemplate.send(internalErrorTopic, errorData) >> Mock(ListenableFuture)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM