简体   繁体   English

Spring注入了模拟Bean

[英]Spring inject mocked Bean

I created a validation constraint depending on a repository. 我根据存储库创建了验证约束。

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());
    }
}

Testing the validator itself is easy by mocking the PersonValidator but I want to test the integration with the validator to check the validation message for example. 通过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());
    }
}

I don't know how to inject a PersonValidator inside the Validator with the mocked repository. 我不知道如何使用PersonValidator的存储库在Validator注入PersonValidator

try this 尝试这个

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

    @Autowired
    private Validator validator;
...

Try running test with SpringJUnit4ClassRunner, and create a mock repository bean and annotate with spring's @Primary annotation or mark as primary in bean definition for test to autowire mock repository. 尝试使用SpringJUnit4ClassRunner运行测试,并创建一个模拟存储库bean并使用spring的@Primary注释进行注释,或者在bean定义中将其标记为primary以进行自动装配模拟存储库。

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

    @Autowired
    private Validator validator;
....

You can create mock repository using mockito factory bean as below 您可以使用mockito工厂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);
    }
....

and then create spring's context file 'test-context.xml' for test repository 然后为测试存储库创建spring的上下文文件'test-context.xml'

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

I prefer setter injection, which makes injecting mocks simple during tests. 我更喜欢setter注入,这使得在测试期间注入模拟更简单。

Or you can also use reflection based injection with a spring util class . 或者您也可以使用spring util类进行基于反射的注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM