Реализация тестовых случаев в тестовом сценарии JGiven - PullRequest
0 голосов
/ 08 октября 2019

Предоставляется файл, содержащий ряд строк, который загружается (в процессе принятия) системой в базу данных. Простой тестовый сценарий, основанный на JGiven, проверяет, соответствует ли количество строк файла соответствующим строкам таблицы. Выполнение теста maven реализации mockup в Java 1.8 обеспечивало следующее (первый вывод):

Test Class: com.testcomp.LoadingTest
 Check Loading Process
   Given that the parameters provided are for an input file ( BRANCH )for a specific date ( 20190105 )was provided
    When the number of file records is calculated
     And the loading is complete
     And the number of table rows loaded is calculated
    Then the no of file records (200) must match the no of table rows (200)

Это допустимая опция, однако, не предоставлять файл для загрузки. Итак, у нас есть два тестовых случая, и тест maven должен обеспечить что-то вроде (второй вывод):

Test Class: com.testcomp.LoadingTest1
 Check Loading Process
   Given that the parameters provided are for an input file ( BRANCH )for a specific date ( 20190105 )
     And the file exists
    When the number of file records is calculated
     And the loading is complete
     And the number of table rows loaded is calculated
    Then the no of file records (200) must match the no of table rows (200)

Test Class: com.testcomp.LoadingTest2
 Check Loading Process
   Given that the parameters provided are for an input file ( BRANCH )for a specific date ( 20190105 )
     And the file does NOT exist
    Then we check nothing

Как нам объединить два тестовых случая, чтобы в зависимости от существования файла у нас был «проход»проверить в любом случае, зная, был ли файл предоставлен или нет? ИЛИ есть ли способ создать нечто похожее на HTML-отчет самой JGiven (третий вывод):

Test Class: com.testcomp.LoadingTest3
 Check Loading Process
   Given that the parameters provided are for an input file ( BRANCH )for a specific date ( 20190105 )
     And the scenario has 2 cases from which only one may be true
    When checking the file's existence is done
     And for case 1 file existence is TRUE
     And for case 1 the number of file records is calculated
     And for case 1 the loading is complete
     And for case 1 the number of table rows loaded is calculated
     And for case 2 file existence is FALSE
    Then for case 1 the no of file records (200) must match the no of table rows (200)
     And for case 2 we check nothing

Реализация для firstВывод выглядит следующим образом:

Класс загрузки-теста

public class LoadingTest
    extends ScenarioTest<GivenWeHaveFile2Load, WhenFileAndDatabaseAreChecked, ThenCheckIfNoOfFileLinesMatchesNoOfTableRows> {

    @ScenarioStage
    WhenFileAndDatabaseAreChecked loadingFinishedState;

    @ScenarioStage
    WhenFileAndDatabaseAreChecked databaseState;

    @Test
    public void Check_Loading_Process() {
        given().that_an_input_file_for_a_specific_date_was_provided("BRANCH", "20190105");
        when().the_number_of_file_records_is_calculated();
        loadingFinishedState
                .and().the_loading_is_complete();
        databaseState
                .and().the_number_of_table_rows_loaded_is_calculated();
        then().the_no_of_file_records_must_match_the_no_of_table_rows();
    }
}

GivenWeHaveFile2Load Class

public class GivenWeHaveFile2Load extends Stage<GivenWeHaveFile2Load> {

    @ProvidedScenarioState
    String properFileName;

    @As( "that the parameters provided are for an input file ($) for a specific date ($) was provided" )
    public GivenWeHaveFile2Load that_an_input_file_for_a_specific_date_was_provided(String filenamePrefix, String dateStringYYYYMMDD) {
        properFileName = filenamePrefix + "_" + dateStringYYYYMMDD + ".txt";
        return self();
    }
}

WhenFileAndDatabaseAreChecked Class

public class WhenFileAndDatabaseAreChecked extends Stage<WhenFileAndDatabaseAreChecked> {

    @ExpectedScenarioState
    String properFileName;

    @ProvidedScenarioState
    int noOfFileRecords;

    @ProvidedScenarioState
    int noOfTableRows;

    // @ExtendedDescription("after we check the number of file lines") // does NOT seem to work..
    public WhenFileAndDatabaseAreChecked the_number_of_file_records_is_calculated() {
        // we'll use properFileName to get noOfFileRecords in the actual implementation
        noOfFileRecords = 200;
        return self();
    }

    public WhenFileAndDatabaseAreChecked the_loading_is_complete() {
        return self();
    }

    public WhenFileAndDatabaseAreChecked the_number_of_table_rows_loaded_is_calculated() {
        noOfTableRows = 200;
        return self();
    }
}

ThenCheckIfNoOfFowLoMoS1029 *

public class ThenCheckIfNoOfFileLinesMatchesNoOfTableRows extends Stage<ThenCheckIfNoOfFileLinesMatchesNoOfTableRows> {

    @ExpectedScenarioState
    int noOfFileRecords;

    @ExpectedScenarioState
    int noOfTableRows;

    @ScenarioState
    CurrentStep currentStep;

    public ThenCheckIfNoOfFileLinesMatchesNoOfTableRows the_no_of_file_records_must_match_the_no_of_table_rows () {
        currentStep.setName("the no of file records (" + noOfFileRecords + ") must match the no of table rows (" + noOfTableRows + ")");
        assert(noOfFileRecords == noOfTableRows);
        return self();
    }
}

1 Ответ

0 голосов
/ 11 октября 2019

Был разработан несколько иной подход, который охватывает потребности:

  • , чтобы узнать, был ли файл предоставлен или нет
  • , чтобы дифференцировать результирующий вывод в зависимости от существования файла

Если файл существует, у нас может быть такой (первый вывод):

Test Class: com.testcomp.LoadingTest
 Check Loading Process
   Given that the parameters provided are for an input file ( BRANCH )for a specific date ( 20190105 )was provided
     And after checking for file existence ( result: true )
    When the number of file records is calculated
     And the loading is complete
     And the number of table rows loaded is calculated
    Then the no of file records (200) must match the no of table rows (200)

Если файл не существует, у нас может быть этот (второй выход):

Test Class: com.testcomp.LoadingTest
 Check Loading Process
   Given that the parameters provided are for an input file ( BRANCH )for a specific date ( 20190105 )was provided
     And after checking for file existence ( result: false )
    Then since we have no file it is OK

Для достижения вышеизложенного, ключевым изменением было определение в классе GivenWeHaveFile2Load метода after_checking_if_file_exists, возвращающего логическое значение для существования файла. Затем результат можно проверить в классе LoadingTest и дифференцировать «сценарий», отображаемый для результата теста. Из начальных четырех (4) классов только WhenFileAndDatabaseAreChecked остается как есть. Код для оставшихся трех (3) приведен ниже.

LoadingTest Класс


public class LoadingTest
    extends ScenarioTest<GivenWeHaveFile2Load, WhenFileAndDatabaseAreChecked, ThenCheckIfNoOfFileLinesMatchesNoOfTableRows> {

    private Boolean fileExists;

    @ScenarioStage
    GivenWeHaveFile2Load CheckingFileExistenceState;

    @ScenarioStage
    WhenFileAndDatabaseAreChecked loadingFinishedState;

    @ScenarioStage
    WhenFileAndDatabaseAreChecked databaseState;

    @ScenarioStage
    ThenCheckIfNoOfFileLinesMatchesNoOfTableRows NoFileProvidedState;

    @Test
    public void Check_Loading_Process() {
        given().that_an_input_file_for_a_specific_date_was_provided("BRANCH", "20190105");
        fileExists = CheckingFileExistenceState
                .and().after_checking_if_file_exists();
        if (fileExists) {
            when().the_number_of_file_records_is_calculated();
            loadingFinishedState
                    .and().the_loading_is_complete();
            databaseState
                    .and().the_number_of_table_rows_loaded_is_calculated();
            then().the_no_of_file_records_must_match_the_no_of_table_rows();
        } else {
            NoFileProvidedState
                    .then().since_we_have_no_file_it_is_OK();
        }
        ;
    }
}

GivenWeHaveFile2Load Класс

public class GivenWeHaveFile2Load extends Stage<GivenWeHaveFile2Load> {

    private Boolean fileExists;

    @ProvidedScenarioState
    String properFileName;

    @ScenarioState
    CurrentStep currentStep;

    public Boolean after_checking_if_file_exists() {
        currentStep.setName("after checking for file existence ( result: " + fileExists + " )");
        return fileExists;
    }

    public void setFileExists(Boolean fileExists) {
        this.fileExists = fileExists;
    }

    @As( "that the parameters provided are for an input file ($) for a specific date ($) was provided" )
    public GivenWeHaveFile2Load that_an_input_file_for_a_specific_date_was_provided(String filenamePrefix, String dateStringYYYYMMDD) {
        properFileName = filenamePrefix + "_" + dateStringYYYYMMDD + ".txt";
        this.setFileExists(Boolean.FALSE); // actual file check goes here
        return self();
    }
}

ThenCheckIfNoOfFileLinesMatchesNoOfTableRows Класс

public class ThenCheckIfNoOfFileLinesMatchesNoOfTableRows extends Stage<ThenCheckIfNoOfFileLinesMatchesNoOfTableRows> {

    @ExpectedScenarioState
    int noOfFileRecords;

    @ExpectedScenarioState
    int noOfTableRows;

    @ScenarioState
    CurrentStep currentStep;

    public ThenCheckIfNoOfFileLinesMatchesNoOfTableRows the_no_of_file_records_must_match_the_no_of_table_rows () {
        currentStep.setName("the no of file records (" + noOfFileRecords + ") must match the no of table rows (" + noOfTableRows + ")");
        assert(noOfFileRecords == noOfTableRows);
        return self();
    }
    public ThenCheckIfNoOfFileLinesMatchesNoOfTableRows since_we_have_no_file_it_is_OK () {
        assert(Boolean.TRUE);
        return self();
    }
}
...