MapStruct Junit-使用CDI注入内部映射器

时间:2018-12-04 13:52:56

标签: java mapstruct

当前具有包含内部Mappers的Mapper(有时本身包含其他内部Mappers)。

它们的定义如下:

@Mapper(componentModel = "cdi", uses = B.class)
public interface A {
    ADto toDto(AEntity entity);
}

@Mapper(componentModel = "cdi")
public interface B {
    BDto toDto(BEntity entity);
}

当应用程序运行时,我可以简单地注入主Mapper A,而不会出现任何问题,并且实体可以转换。

但是,通过JUnit,我似乎无法弄清楚如何实例化内部映射器。

public class InformationChassisMapperTest {
    @InjectMocks
    public A mapper = new AImpl();

    public AEntity;
    @Before
    public void init() {
       AEntity = new AEntity();
       // fill entity...
    }

    @Test
    public void test() {
       ADto = mapper.toDto(AEntity);
       // asserts...
    }
}

我得到了NPE,因为在映射过程中没有实例化内部映射器B。由于生成的A映射器类使用@Inject B,因此在我的JUnit测试期间,CDI Bean映射处于关闭状态(无Arquillian)。我该如何模拟或注入或实例化第二个映射器以通过测试?

我看过其他答案,但它们仅涵盖Spring。

2 个答案:

答案 0 :(得分:1)

在不创建CDI上下文的情况下,一个选择是使用Mockito定义内部类,例如:

@Spy
private B uses = Mappers.getMapper(B.class);

@InjectMocks
private A mapper = Mappers.getMapper(A.class);

@Test
public void test() {
   ADto = mapper.toDto(AEntity);
   // asserts...
}

这将在使用B时为A设置内部映射器。

答案 1 :(得分:0)

我建议不要嘲笑Mapper并使用CDI设置一个可以正确创建所有Mappers的测试(不具备CDI经验以提供解决方案)。

话虽如此,您可以使用1.3中的Mapper#injectionStrategy。您可以使用构造函数注入并将模拟注入其中。