All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tngtech.jgiven.spock.ScenarioSpec.groovy Maven / Gradle / Ivy

The newest version!
package com.tngtech.jgiven.spock

import com.google.common.reflect.TypeToken
import com.tngtech.jgiven.annotation.DoNotIntercept
import com.tngtech.jgiven.impl.Scenario
import com.tngtech.jgiven.junit.JGivenClassRule
import com.tngtech.jgiven.spock.junit.JGivenSpockMethodRule
import net.bytebuddy.ByteBuddy
import net.bytebuddy.description.annotation.AnnotationDescription
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy
import net.bytebuddy.implementation.SuperMethodCall
import net.bytebuddy.matcher.ElementMatchers
import org.junit.ClassRule
import org.junit.Rule
import spock.lang.Shared
import spock.lang.Specification

/**
 * ScenarioSpec to use JGiven with Spock2 Framework
 *
 * @since 1.2.0
 */
class ScenarioSpec extends Specification {
    @ClassRule @Shared JGivenClassRule writerRule = new JGivenClassRule()
    @Rule JGivenSpockMethodRule scenarioRule = new JGivenSpockMethodRule(createScenario())

    GIVEN given() {
        getScenario().given()
    }

    WHEN when() {
        getScenario().when()
    }

    THEN then() {
        getScenario().then()
    }

    Scenario getScenario() {
        (Scenario) scenarioRule.getScenario()
    }

    Scenario createScenario() {
        Class givenClass = addDoNotInterceptToMetaClass(new TypeToken(getClass()) {}.getRawType())
        Class whenClass = addDoNotInterceptToMetaClass(new TypeToken(getClass()) {}.getRawType())
        Class thenClass = addDoNotInterceptToMetaClass(new TypeToken(getClass()) {}.getRawType())

        new Scenario(givenClass, whenClass, thenClass)
    }

    private  Class addDoNotInterceptToMetaClass(Class clazz) {
        AnnotationDescription doNotIntercept = AnnotationDescription.Builder.ofType(DoNotIntercept.class).build()
        def clazzA = clazz.metaClass.getTheClass()
        new ByteBuddy()
                .subclass(clazzA)
                .method(ElementMatchers.named("getMetaClass"))
                .intercept(SuperMethodCall.INSTANCE)
                .annotateMethod(doNotIntercept)
                .make()
                .load(clazzA.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                .getLoaded() as Class
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy