本文介绍了Mockito:模拟对象未注入构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个构造函数:

public class AuditsLoaderService {
    public AuditsLoaderService(
        BackOfficeProperties backOfficeProperties,
        FrontOfficeInterfaceService frontOfficeService,
        AuditService auditService,
        I18nResourceBundleMessageSource messageSource,
        MonitorService monitor
    ) {
      // some code
    }
}

AuditService 是:

public class AuditService {
    public AuditService(
        BackOfficeProperties backOfficeProperties,
        AuditFactory auditFactory,
        AuditDao auditDAO,
        RedisDao auditRedisDao,
        ObjectMapper objectMapper,
        I18nResourceBundleMessageSource messageSource
    ) {

进入我的测试:

@RunWith(MockitoJUnitRunner.class)
public class MalformedAuditsTest {

    @Mock
    private BackOfficeProperties backOfficeProperties;
    @Mock
    private AuditFactory auditFactory;
    @Mock
    private AuditDao auditDao;
    @Mock
    private RedisDao redisDao;
    @Mock
    private ObjectMapper objectMapper;
    @Mock
    private I18nResourceBundleMessageSource i18nResourceBundleMessageSource;
    @Mock
    private MonitorService monitorService;
    @InjectMocks
    @Spy
    private AuditService auditService;
    @InjectMocks
    private FrontOfficeInterfaceService frontOfficeService;
    @InjectMocks
    private AuditsLoaderService auditsLoaderService;

}

尽管如此,由于 auditServicenull.

Nevertheless, I'm getting an NulPointerException inside my AuditsLoaderService since auditService is null.

好像没有注入.

我已将其注释为:

@InjectMocks
@Spy
private AuditService auditService;

我应该添加更多代码/注释吗?

Should I add some more code/annotation?

编辑

我刚刚意识到 frontOfficeServiceauditSerice 都没有注入.

I've just realized neither frontOfficeService neither auditSerice are injected on.

所以,似乎所有 @InjectMocks 字段都没有注入其他字段

So, it seems all @InjectMocks fields are not injected on others ones

推荐答案

尝试添加:

@Mock
private ObjectMapper objectMapper;

因为您的 AuditService 构造函数需要它

because your AuditService constructor requires it

编辑:通过在相应的构造函数中传递模拟来手动创建对象可能更容易

EDIT: It's probably easier to create objects manually by passing mocks in corresponding constructor

这篇关于Mockito:模拟对象未注入构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:18