Упрощение кода для тестирования содержимого каталога / файлов - PullRequest
1 голос
/ 18 апреля 2020

У меня есть следующий тестовый код, который проверяет содержимое определенной структуры каталогов

assertThat(install_should_not_fail).isDirectory().satisfies(isnf -> {
  assertThat(new File(isnf, "maven-metadata-local.xml")).isNotEmpty();
  assertThat(new File(isnf, "1.0")).isDirectory().satisfies(v10 -> {
    assertThat(v10).satisfies(file -> {
      assertThat(new File(file, "install_should_not_fail-1.0.jar")).isNotEmpty();
      assertThat(new File(file, "install_should_not_fail-1.0.pom")).isNotEmpty();
      assertThat(new File(file, "_remote.repositories")).isNotEmpty();
    });
  });
});

, и у меня есть несколько тестов, которые делают очень похожие вещи. Вопрос в том, можно ли это сделать проще (я знаю, что мог бы реорганизовать метод, который содержит именно этот код), но меня больше интересует упрощение приведенного выше кода с использованием AssertJ, если это возможно?

Ответы [ 2 ]

2 голосов
/ 19 апреля 2020

Если вам не нужно проверять, не являются ли файлы непустыми, Files :: fileNamesIn может пригодиться. Вы можете сделать что-то вроде:

assertThat(Files.filesNamesIn(dir, /* recursive */ true)).contains(
  basePath + "/maven-metadata-local.xml",
  basePath + "/1.0/install_should_not_fail-1.0.jar",
  basePath + "/1.0/install_should_not_fail-1.0.pom",
  basePath + "/1.0/_remote.repositories")

В противном случае вы можете изменить этот шаблон в свое собственное утверждение. Например, вот утверждение, которое проверяет, что данные пути представляют непустые, читаемые файлы внутри каталога:

public class MyAssertions extends Assertions {
    public static MyFileAssert assertThat(File actual) {
        return MyFileAssert.assertThat(actual);
    }
}

public class MyFileAssert extends AbstractFileAssert<MyFileAssert> {
    public MyFileAssert(File actual) {
        super(actual, MyFileAssert.class);
    }

    public static MyFileAssert assertThat(File actual) {
        return new MyFileAssert(actual);
    }

    public MyFileAssert containsReadableNonEmptyFiles(String... paths) {
        isDirectory();

        List<String> nonExistent = new ArrayList<>();
        List<String> nonFiles = new ArrayList<>();
        List<String> nonReadable = new ArrayList<>();
        List<String> empty = new ArrayList<>();

        for (String path : paths) {
            File file = new File(actual, path);

            if (!file.exists()) {
                nonExistent.add(path);
                continue;
            }

            if (!file.isFile()) {
                nonFiles.add(path);
                continue;
            }

            if (!file.canRead()) {
                nonReadable.add(path);
                continue;
            }

            if (file.length() == 0) {
                empty.add(path);
            }
        }

        if (!(nonExistent.isEmpty() && nonFiles.isEmpty() && nonReadable.isEmpty() && empty.isEmpty())) {
            StringBuilder failMessage = new StringBuilder()
                    .append("Expected directory '")
                    .append(actual)
                    .append("' to contain the following readable, non-empty files:\n");

            for (String path : paths) {
                failMessage.append("  ")
                        .append(path)
                        .append("\n");
            }


            if (!nonExistent.isEmpty()) {
                failMessage.append("The following files don't exist:\n");

                for (String path : nonExistent) {
                    failMessage.append("  ")
                            .append(path)
                            .append("\n");
                }

            }

            // The rest left out for brevity.

            failWithMessage(failMessage.toString());
        }

        return this;
    }
}

Пример использования приведенного выше примера:

assertThat(install_should_not_fail).containsReadableNonEmptyFiles(
  "maven-metadata-local.xml",
  "1.0/install_should_not_fail-1.0.jar",
  "1.0/install_should_not_fail-1.0.pom",
  "1.0/_remote.repositories")

Вы можете узнать больше о пользовательских утверждениях AssertJ здесь .

2 голосов
/ 19 апреля 2020

Я бы предложил подход, который не использует satisfies, чтобы избежать вложенных блоков:

assertThat(install_should_not_fail).isDirectory();
assertThat(new File(install_should_not_fail, "maven-metadata-local.xml")).isNotEmpty();

File v10 = new File(install_should_not_fail, "1.0");
assertThat(v10).isDirectory();
assertThat(new File(v10, "install_should_not_fail-1.0.jar")).isNotEmpty();
assertThat(new File(v10, "install_should_not_fail-1.0.pom")).isNotEmpty();
assertThat(new File(v10, "_remote.repositories")).isNotEmpty();

Мне кажется, что это делает код немного легче и более читабельным (по крайней мере для меня).

Более того, я думаю, что это хороший кандидат для мягких утверждений, так что все ошибки подтверждений сообщаются вместо сбоев при первом.

...