Mockito:模拟对象未注入构造函数参数

时间:2019-01-31 10:07:25

标签: java 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;

}

尽管如此,由于我的{strong> NulPointerExceptionAuditsLoaderService ,所以我的auditService中有null

似乎没有注入。

我将其注释为:

@InjectMocks
@Spy
private AuditService auditService;

我应该再添加一些代码/注释吗?

编辑

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

因此,似乎所有@InjectMocks字段都没有注入到其他字段上

1 个答案:

答案 0 :(得分:-1)

尝试添加:

@Mock
private ObjectMapper objectMapper;

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

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