Интеграционный тест и build.gradle Java Spring - PullRequest
0 голосов
/ 03 апреля 2020

Я пытаюсь написать интеграционные тесты для своего сервиса.

Я попытался написать простой тест в качестве первого теста. Мой класс WebControllerIT выглядит следующим образом:

@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = SocialInteractionApplication.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebControllerIT {

  @LocalServerPort private int webServerPort;

  @Autowired private AppUserRepository AppUserRepository;

  @Autowired private WebController webController;

  private RestTemplate restTemplate = new RestTemplate();

  private String createURLWithPort(String uri) {
    return "http://localhost:" + webServerPort + uri;
  }

  @Test
  public void testSetNewAppUser() {

    HttpEntity<String> entity = new HttpEntity<String>(null,null);

    ResponseEntity<String> response =
        restTemplate.exchange(
            createURLWithPort("/{RobsAndroid}/setNewAppUser/{Rob}"),
            HttpMethod.GET,
            entity,
            String.class);

    String expected = "New AppUser: " + "RobsAndroid"+ " set OK.";
    assertEquals(expected,response.getBody());
    assertEquals(HttpStatus.OK,response.getStatusCode());
  }
}

Однако я получаю сообщение об ошибке:

Execution failed for task ':integrationTest'.
> No tests found for given includes: [com.socialinteraction.componenttests.WebControllerIT.testSetNewAppUser](filter.includeTestsMatching)

Кажется, я не могу понять, что происходит, какие-то идеи?

Чтобы дать больше контекста, я не знал, с чего начать тестирование компонентов. Это включает: где они должны быть расположены, какие зависимости они должны иметь, как их запускать в сборке gradle et c. Я следовал учебному пособию, и мой файл build.gradle закончился следующим образом:

plugins {
    id 'org.springframework.boot' version '2.2.5.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.socialinteraction'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

sourceSets {
    integrationTest {
        java {
            compileClasspath += main.output + test.output
            runtimeClasspath += main.output + test.output
            srcDir file('src/integration-test/java')
        }
        resources.srcDir file('src/integration-test/resources')
    }
}

configurations {
    integrationTestCompile.extendsFrom testCompile
    integrationTestRuntime.extendsFrom testRuntime
    integrationTestImplementation.extendsFrom testImplementation
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
//    testCompile "org.powermock:powermock-module-junit4:1.6.4"
//    testCompile 'org.mockito:mockito-core:2.7.22'
    implementation 'org.jetbrains:annotations:15.0'
    implementation 'junit:junit:4.12'
    implementation 'org.testng:testng:6.9.6'
    implementation 'junit:junit:4.12'
    implementation 'junit:junit:4.12'
    implementation 'org.testng:testng:6.9.6'
}

test {
    useJUnitPlatform()
}

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
}


check.dependsOn integrationTest
integrationTest.mustRunAfter test

Я по существу убедился, что зависимости интеграционных тестов были унаследованы от модульных тестов, появился новый тип intergrationTest и что он был запущен в сборке после модульных тестов.

Дополнительный вопрос - не уверен, что testRuntime, testImplementation и другие типы зависимостей все необходимы / правильны, поэтому хорошая ссылка для объяснения этого была бы полезна, если у кого-то она есть?

Большое спасибо за вашу помощь!

...