【问题标题】:@Spy not working when annotated on two lists@Spy 在两个列表上注释时不起作用
【发布时间】:2017-09-08 14:02:17
【问题描述】:

这是我的 PersonServiceImpl 类。在保存任何人之前,我想运行一些实现 PersonValidator 的验证器。我还自动装配了 PersonStatusChangeValidator 以在不同的方法中使用。

public class PersonServiceImpl implements PersonService {

    @Autowired
    PersonDao personDao;

    @Autowired
    List<PersonStatusChangeValidator> statusChangeValidators;

    @Autowired
    List<PersonValidator> personValidators;

    @Override
    public Person save(Person person) {
        for(PersonValidator validator: personValidators){
            validator.validate(person);
        }
        personDao.save(person);
        return person;
    }
}

这里我正在编写测试来验证是否调用了验证器。

@RunWith(PowerMockRunner.class)
public class PersonServiceImplTest {

    @Mock
    private PersonDao personDao;

    @Mock
    private PersonValidator personValidator;

    @Mock
    private PersonStatusChangeValidator statusChangeValidator;

    @Spy
    private List<PersonStatusChangeValidator> statusChangeValidators = new ArrayList<>();

    @Spy
    private List<PersonValidator> personValidators = new ArrayList<>();

    @InjectMocks
    private PersonServiceImpl personService;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);

        personValidators.add(personValidator);
        statusChangeValidators.add(statusChangeValidator);
    }

    @Test
    public void testCreatePerson() throws Exception {
        personService.save(new Person());
        verify(personValidator, times(1)).validate(any(Person.class));
    }
}

问题是personValidatorsstatusChangeValidators 在我运行测试时为空。当测试中有一个 @Spy 注释时,它工作正常。需要一些帮助才能知道我哪里做错了。

【问题讨论】:

  • 你用的是spring boot吗?
  • 不是答案,但如果您使用了构造函数注入,一切都会变得更简单。你可以使用new PersonServiceImpl(personDao, Collections.singletonList(personValidator), Collections.singletonList(statusChangeValidator))
  • Plog 不,我没有使用弹簧靴

标签: java unit-testing junit mockito powermockito


【解决方案1】:

您的测试没有显示任何对静态或决赛的嘲弄,所以我想知道您为什么使用@RunWith(PowerMockRunner.class)

我已获取您的代码并成功运行它,只需进行一项更改:将 @RunWith(PowerMockRunner.class) 替换为 @RunWith(MockitoJUnitRunner.class)

因此,除非您的测试有其他方面需要 PowerMock,否则我建议您使用MockitoJUnitRunner 运行您的测试用例。如果您的测试的某些方面需要 PowerMock,那么我建议使用显式构造函数注入注入 statusChangeValidatorspersonValidators 实例(即@JB Nizet 在上面的评论中建议的内容),这样您就不必依赖在@InjectMocks

FWIW,有一个 open issue against PowerMock 表示无法将 @InjectMocks 应用于带有 @Spy 注释的字段。

【讨论】:

    猜你喜欢
    • 2013-04-15
    • 2014-03-24
    • 2011-01-29
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2011-12-19
    • 2013-09-20
    相关资源
    最近更新 更多