1

Trying to do some tests with MapStruct here. I have the following classes:

Test Class

RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MapperTests {

@Autowired
private UsuarioMapper usuarioMapper; //Can't autowire(No typo found)

@Test
public void dadoUsuarioSalvarDTO_quandoMapeioParaUsuario_entaoRetornaUsuario(){

    //Dado
    UsuarioSalvarDTO usuarioSalvarDTO = new UsuarioSalvarDTO();
    usuarioSalvarDTO.setEmail("test@test.com");
    usuarioSalvarDTO.setSenha("123456789");
    usuarioSalvarDTO.setStatus(TipoStatus.ATIVO);

    Usuario usuario = usuarioMapper.toEntity(usuarioSalvarDTO);

    Assert.assertEquals(usuario.getEmail(), "test@test.com");
    Assert.assertEquals(usuario.getSenha(), "123456789");
    Assert.assertEquals(usuario.getStatus(), TipoStatus.ATIVO);


}
}

Mapper

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN)
public interface UsuarioMapper {

@Mappings({
        @Mapping(target = "id", ignore = true),
        @Mapping(target = "createdAt", ignore = true),
        @Mapping(target = "updatetAt", ignore = true),
        @Mapping(source="usuarioSalvarDTO.email", target = "email")
})
Usuario toEntity(UsuarioSalvarDTO usuarioSalvarDTO);

}

Consider Models here

Generated UsuarioMapperImpl:

@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2018-11-24T00:40:25-0200",
comments = "version: 1.2.0.Final, compiler: javac, environment: Java 1.8.0_181 (Oracle Corporation)"
)
@Component
public class UsuarioMapperImpl implements UsuarioMapper {

@Override
public Usuario toEntity(UsuarioSalvarDTO usuarioSalvarDTO) {
    if ( usuarioSalvarDTO == null ) {
        return null;
    }

    Usuario usuario = new Usuario();

    usuario.setEmail( usuarioSalvarDTO.getEmail() );
    usuario.setSenha( usuarioSalvarDTO.getSenha() );
    usuario.setStatus( usuarioSalvarDTO.getStatus() );

    return usuario;
    }
}

When i try to run the test, he gives the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error         creating bean with name 'br.com.financeiroAdam.demo.MapperTests': Unsatisfied dependency expressed through field 'usuarioMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.financeiroAdam.demo.mapper.UsuarioMapper' available: expected at least 1 bean which qualifies as autowire candidate.

@Autowire in MapperTest don't work. It claims: 'Could not autowire. No beans of 'UsuarioMapper' type found.'

Already tried:

  • gradle build (no errors)
  • gradle build -x test (no errors)
  • Invalidate Caches / Restart
  • Re-import project

Using:

  • IntelliJ
  • Gradle
  • Spring
  • Lombok

build.gradle

buildscript {
ext {
    springBootVersion = '2.1.0.RELEASE'
}
repositories {
    mavenCentral()
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}

plugins {
id 'net.ltgt.apt' version '0.8'
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'br.com.financeiroAdam'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
mavenCentral()
}


dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.springframework.boot:spring-boot-starter-web')

compileOnly('org.projectlombok:lombok:1.18.2')

compile 'org.mapstruct:mapstruct-jdk8:1.2.0.Final'
testImplementation('org.springframework.boot:spring-boot-starter-test')

apt('org.projectlombok:lombok:1.18.2')
apt('org.mapstruct:mapstruct-processor:1.2.0.Final')

}

Tried everything. I think the mapstruct simply does not want to work. Any solutions?

DaMews
  • 11
  • 2
  • Hello, could you try the solution in https://stackoverflow.com/a/52884637/4611077 . – DonatasD Nov 24 '18 at 04:34
  • In addition to the remark of @DonatasD above: MapStruct is a code generator. If the code is not there when your tests execute, there's nothing to autowire – Sjaak Nov 24 '18 at 10:46
  • @DonatasD still dont finding bean of type UsuarioMapper on Autowire – DaMews Nov 24 '18 at 10:54
  • @sjaak But the Impl class is generated. How Autowire cannot find it? – DaMews Nov 24 '18 at 10:55

2 Answers2

0
//Use @Mock instead of @Autowired

@Mock
private UsuarioMapper usuarioMapper; 

//In test method use the below
    Mockito.doReturn(info).when(usuarioMapper).XYXMethod(ArgumentMatchers.argThat(t24InfoMatcher));
Roshan Oswal
  • 111
  • 1
  • 2
  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context. – Robert Columbia Nov 25 '18 at 23:50
  • This doesn't solve the question. Instead of fixing the autowiring, it mocks the class that the OP tried to inject. – mapto May 08 '19 at 10:08
0

Add config file that contains:

       @ComponentScan("The path to mapstract classes")

       @Configuration
       public class MapstructConfig {   
       }

And add to spring.factories file:

       org.springframework.boot.autoconfigure.EnableAutoConfiguration=
       "The path of the config class that created"
Michal
  • 111
  • 1
  • 9
  • Hello and welcome to SO, please edit your answer with formatting and add a complete example (merge your comment). – Frieder Feb 11 '20 at 15:10