0

你好,我有一门课,我想测试。此类有一个自动装配的 DAO 对象,该对象已在@PostConstruct方法中使用,但我想使用模拟而不是真实对象有没有办法。这是一个例子:

@Autowired
PersonDao personDao;
//Constructor 
public Person()
{
    //Do stuff
}

@PostConstruct
void init()
{
    //I need it to be a mock
    personDao.add(new Person());
}
4

1 回答 1

1

如果你想使用 mockedPersonDao你有几个选择:

  • PersonDaomock 定义为具有primary="true"属性的 Spring bean,以便它优先于普通 bean

  • 将自动装配移动到构造函数并Person通过提供模拟手动创建:

    PersonDao personDao;
    
    @Autowired
    public Person(PersonDao personDao)
    {
        this.personDao = personDao;
    }
    

    然后:

    new Person(personDaoMock)
    

    并且不要依赖Spring。

  • 您可以使用以下方法修改私有字段ReflectionTestUtils

    ReflectionTestUtils.setField(person, "personDao", mock);
    
于 2012-10-02T12:21:08.887 回答