@MicronautTest не запускает встроенный сервер - PullRequest
1 голос
/ 09 апреля 2019

Я пишу тест Спока для контроллеров в приложении, использующем Micronaut. При использовании @MicronautTest(application=Application) выдается исключение с сообщением @MicronautTest used on test but no bean definition for the test present..

При проверке кода я вижу следующие 2 причины, по которым Micronaut выдает это исключение. От io.micronaut.test.extensions.spock.MicronautSpockExtension:

    if (this.specDefinition == null) {
        if (!this.isTestSuiteBeanPresent((Class)spec.getReflection())) {
          throw new InvalidSpecException("@MicronautTest used on test but no bean definition for the test present. This error indicates a misconfigured build or IDE. Please add the 'micronaut-inject-java' annotation processor to your test processor path (for Java this is the testAnnotationProcessor scope, for Kotlin kaptTest and for Groovy testCompile). See the documentation for reference: https://micronaut-projects.github.io/micronaut-test/latest/guide/");
        }
    ...
    }

Моя конфигурация POM:

     <plugin>
        <groupId>org.codehaus.gmavenplus</groupId>
        <artifactId>gmavenplus-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <goals>
              <goal>addTestSources</goal>
              <goal>addSources</goal>
              <goal>compileTests</goal>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
          <encoding>UTF-8</encoding>
          <compilerArgs>
            <arg>-parameters</arg>
          </compilerArgs>
          <annotationProcessorPaths>
            <path>
              <groupId>org.mapstruct</groupId>
              <artifactId>mapstruct-processor</artifactId>
              <version>${mapstruct.version}</version>
            </path>
            <path>
              <groupId>io.micronaut</groupId>
              <artifactId>micronaut-inject-java</artifactId>
              <version>${micronaut.version}</version>
            </path>
            <path>
              <groupId>io.micronaut</groupId>
              <artifactId>micronaut-validation</artifactId>
              <version>${micronaut.version}</version>
            </path>
          </annotationProcessorPaths>
        </configuration>
        <executions>
          <execution>
            <id>test-compile</id>
            <goals>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <compilerArgs>
                <arg>-parameters</arg>
              </compilerArgs>
              <annotationProcessorPaths>
                <path>
                  <groupId>org.mapstruct</groupId>
                  <artifactId>mapstruct-processor</artifactId>
                  <version>${mapstruct.version}</version>
                </path>
                <path>
                  <groupId>io.micronaut</groupId>
                  <artifactId>micronaut-inject-java</artifactId>
                  <version>${micronaut.version}</version>
                </path>
              </annotationProcessorPaths>
            </configuration>
          </execution>
        </executions>
      </plugin>

Если я не определяю аннотацию теста @MicronautTest, кажется, что приложение даже не запускается.

Ниже приведен код спецификации:

@MicronautTest(application= Application)
@PropertySource(value = [
        @Property(name='spec.name', value = 'EndpointSpec'),
        @Property(name = 'endpoints.health.details-visible', value = 'ANONYMOUS'),
        @Property(name = MongoSettings.EMBEDDED, value = 'true'),
])
class EndpointSpec extends Specification {

    @Inject
    EmbeddedServer embeddedServer
    @Inject
    ApplicationContext applicationContext

    @Unroll
    def "test health endpoint is working"() {
        given: 'a RxHttpClient'
        URL server = embeddedServer.getURL()
        RxHttpClient client = new DefaultHttpClient(server, new DefaultHttpClientConfiguration(), '/management')

        when: '/health is called'
        HttpResponse response = client.toBlocking().exchange('/health')

        then: 'response is 200 OK and contains valid headers'
        response.status == HttpStatus.OK
        response.headers.size() == 5
        response.headers.contains('uber-trace-id')
        response.headers.contains('Date')
        response.headers.contains('content-type') && response.headers.get('content-type') == MediaType.APPLICATION_JSON
        response.headers.contains('content-length')
        response.headers.contains('connection')

        //and: 'response contains valid HealthResult'
        //HealthResult healthResult = response.body()
        // Want to validate the health result here but nothing is present in body

    }
}

Как я могу либо определить значение specDefinition, либо пометить тест таким образом, чтобы он присутствовал как определение бина, и какова причина такого поведения. Любая помощь будет принята с благодарностью.

1 Ответ

1 голос
/ 11 апреля 2019

Микронавт-тест делает сами тесты бобов. Чтобы Groovy-тест был бином, вам нужно иметь micronaut-inject-groovy на пути компиляции для test.

...