如何在Gradle构建中为测试范围映射器接口生成Mapstruct映射器实现?

时间:2019-01-28 11:06:42

标签: java gradle mapstruct

我有一个简单的Java单一模块Gradle项目,其中使用Mapstruct进行Java映射。我的build.gradle看起来像这样:

plugins {
    id 'java-library'
    id 'groovy'
    id 'net.ltgt.apt' version '0.20'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'org.mapstruct:mapstruct-jdk8:1.2.0.Final'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.2.0.Final'

    testImplementation 'org.codehaus.groovy:groovy-all:2.5.5'

    // Use the awesome Spock testing and specification framework even with Java
    testImplementation 'org.spockframework:spock-core:1.2-groovy-2.5'
    testImplementation 'junit:junit:4.12'
}

sourceSets {
    main {
        java {
            srcDirs "${project.buildDir}/generated/sources/annotationProcessor/java/main"
        }
    }
    test {
        java {
            srcDirs "${project.buildDir}/generated/sources/annotationProcessor/java/test"
        }
    }
}

我的源文件夹包含以下Java源代码:

src
├── main
│   ├── java
│   │   └── ch
│   │       └── silviowangler
│   │           ├── Person.java
│   │           ├── SomeMapper.java
│   │           └── User.java
│   └── resources
└── test
    ├── groovy
    │   └── ch
    │       └── silviowangler
    ├── java
    │   └── ch
    │       └── silviowangler
    │           └── YoloMapper.java
    └── resources

SomeMapper是一个简单的映射器界面,看起来像这样

@Mapper
public interface SomeMapper {

    @Mappings({
            @Mapping(target = "firstName", source = "nickname"),
            @Mapping(target = "surname", ignore = true),
            @Mapping(target = "dateOfBirth", ignore = true)
    })
    Person fromString(User user);
}

位于测试范围内的YoloMapper看起来像这样

@Mapper
public interface YoloMapper {

    String fromLocalDate(LocalDate localDate);
}

当我运行./gradlew clean cTJ时,构建成功完成,并且注释处理器为SimpleMapper生成了一个映射器实现,但没有为YoloMapper生成任何内容。构建后的build文件夹如下

build
├── classes
│   └── java
│       ├── main
│       │   └── ch
│       │       └── silviowangler
│       │           ├── Person.class
│       │           ├── SomeMapper.class
│       │           ├── SomeMapperImpl.class
│       │           └── User.class
│       └── test
│           └── ch
│               └── silviowangler
│                   └── YoloMapper.class
├── generated
│   └── sources
│       └── annotationProcessor
│           └── java
│               ├── main
│               │   └── ch
│               │       └── silviowangler
│               │           └── SomeMapperImpl.java
│               └── test
└── tmp
    ├── compileJava
    └── compileTestJava

如何让Gradle告诉注释处理器在测试范围内生成Mapstruct映射器实现?

1 个答案:

答案 0 :(得分:3)

您需要配置testAnnocationProcess配置,如下所示:

dependencies{

    // for Main sources set
    implementation 'org.mapstruct:mapstruct-jdk8:1.2.0.Final'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.2.0.Final'

    // for Test sources set  
    testAnnotationProcessor "org.mapstruct:mapstruct-processor:1.2.0.Final"

}