How to get the exception that was thrown when a Cucumber test failed in Java?

前端 未结 7 753
攒了一身酷
攒了一身酷 2021-01-13 02:07

I can perform actions on test failure by using:

@After
public void afterTest(Scenario scenario) {
    if (scenario.isFailed()) {
        /*Do stuff*/
    }
}         


        
7条回答
  •  广开言路
    2021-01-13 02:48

    This is the workaround for cucumber-java version 4.8.0 using reflection.

    import cucumber.api.Result;
    import io.cucumber.core.api.Scenario;
    import io.cucumber.core.logging.Logger;
    import io.cucumber.core.logging.LoggerFactory;
    import io.cucumber.java.After;
    import org.apache.commons.lang3.ClassUtils;
    import org.apache.commons.lang3.reflect.FieldUtils;
    
    import java.io.IOException;
    import java.lang.reflect.Field;
    import java.net.URL;
    import java.util.ArrayList;
    
    @After
    public void afterScenario(Scenario scenario) throws IOException {
        if(!scenario.getStatus().isOk(true)){
            logError(scenario);
        }
    }
    
    private static void logError(Scenario scenario) {
        try {
            Class clasz = ClassUtils.getClass("cucumber.runtime.java.JavaHookDefinition$ScenarioAdaptor");
            Field fieldScenario = FieldUtils.getField(clasz, "scenario", true);
            fieldScenario.setAccessible(true);
            Object objectScenario =  fieldScenario.get(scenario);
    
            Field fieldStepResults = objectScenario.getClass().getDeclaredField("stepResults");
            fieldStepResults.setAccessible(true);
    
            ArrayList results = (ArrayList) fieldStepResults.get(objectScenario);
            for (Result result : results) {
                if (result.getError() != null) {
                    LOGGER.error(String.format("Error Scenario: %s", scenario.getId()), result.getError());
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error while logging error", e);
        }
    }
    

提交回复
热议问题