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

tw.teddysoft.ezspec.extension.junit5.Junit5Examples Maven / Gradle / Ivy

The newest version!
package tw.teddysoft.ezspec.extension.junit5;


import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import tw.teddysoft.ezspec.keyword.Example;
import tw.teddysoft.ezspec.keyword.Examples;
import tw.teddysoft.ezspec.keyword.table.Table;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * {@code Junit5Examples} is a class for representing Gherkin examples for Junit.
 *
 * @author Teddy Chen
 * @since 1.0
 */
public abstract class Junit5Examples implements Examples, ArgumentsProvider {

    @Override
    public String getName() {
        String simpleName = this.getClass().getSimpleName();
        return simpleName.substring(0, 1).toUpperCase() +
                simpleName.substring(1).replace("_examples", "").replaceAll("_", " ");
    }

    /**
     * Transforms a class into an example.
     *
     * @param cls the cls
     * @return the example
     */
    public static Example get(Class cls) {
        try {
            Class clazz = Class.forName(cls.getTypeName());
            Constructor constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
            Junit5Examples instance = (Junit5Examples) constructor.newInstance();
            return instance.getExample();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Stream provideArguments(ExtensionContext extensionContext) {
        List arguments = new ArrayList<>();
        getTable().rows().forEach( row -> {
            arguments.add(Arguments.of(row.columns().toArray()));
        });
        return arguments.stream();
    }

    @Override
    public Table getTable() {
        return new Table(getExamplesRawData());
    }

    abstract protected String getExamplesRawData();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy