Spring注入了模拟Bean

时间:2014-04-24 02:01:52

标签: java spring validation

我根据存储库创建了验证约束。

public class PersonValidator implements ConstraintValidator {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public void initialize(PersonValidator personValidator) {

    }

    @Override
    public boolean isValid(Person person, ConstraintValidatorContext context) {
        return null != repository.findByName(person.getName());
    }
}

通过模拟PersonValidator来测试验证器本身很容易,但我想测试与验证器的集成以检查验证消息,例如。

public class PersonValidatorTest {

    @Autowired
    private Validator validator;

    @Test
    public void integration() {
        Person person = new Person();
        person.setName("person");

        Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person);
        Assert.assertEquals(0, constraintViolations.size());
    }
}

我不知道如何在PersonValidator内部使用模拟的存储库注入Validator

3 个答案:

答案 0 :(得分:1)

试试这个

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "context.xml")
public class PersonValidatorTest {

    @Autowired
    private Validator validator;
...

答案 1 :(得分:1)

尝试使用SpringJUnit4ClassRunner运行测试,并创建一个模拟存储库bean并使用spring的@Primary注释进行注释,或者在bean定义中将其标记为primary以进行自动装配模拟存储库。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/context.xml", "/test-context.xml"})
public class PersonValidatorTest {

    @Autowired
    private Validator validator;
....

您可以使用mockito factory bean创建模拟存储库,如下所示

public class MockitoFactoryBean<T> implements FactoryBean<T> {
    private Class<T> classToBeMocked;

    public MockitoFactoryBean(Class<T> classToBeMocked) {
        this.classToBeMocked = classToBeMocked;
    }

    @Override
    public T getObject() throws Exception {
        return Mockito.mock(classToBeMocked);
    }
....

然后创建spring的上下文文件&test-context.xml&#39;用于测试库

<bean id="mockRepository" primary="true" class="com.test.mock.MockitoFactoryBean">
    <constructor-arg value="com....PersonRepository"/>
</bean>

答案 2 :(得分:0)

我更喜欢setter注入,这使得在测试期间注入模拟变得简单。

或者您也可以使用基于反射的注射spring util class