繁体   English   中英

春季集成测试:使用MockitoJUnitRunner时注入@Value

[英]Spring integration tests: inject @Value while using MockitoJUnitRunner

下面的示例工作正确。 问题是我确实需要@InjectMocks批注。 当我更换SpringJUnit4ClassRunner.classMockitoJUnitRunner.class一切休息( bar = null ,而不是testValue )。

怎么修?

//@RunWith(MockitoJUnitRunner.class) // not work (
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooTest.Config.class)
@TestPropertySource(properties = {
        "some.bar.value=testValue",
})
public class FooTest {

    @Value("${some.bar.value}")
    String bar;

    @Test
    public void testValueSetup() {
        assertEquals("testValue", bar);
    }

    @Configuration
    static class Config {

        @Bean
        public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    }
}

您应该能够使用ClassRule和Rule的组合来启用与SpringRunner相同的功能。

    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

然后像平常一样使用MockitoRunner。

此外,您始终可以直接使用Mockito.mock等直接模拟依赖Mockito.mock 。注解方法,如果测试不简单(尤其是测试方法),则稍微简洁一些会导致一些烦人的运行时问题。 @InjectMocks的情况下。

好奇为什么在SpringBoot项目中需要Mockito运行器? 您可以在需要时使用MockBeans模拟出Spring Bean。 闻起来像XY问题,因为我从未使用过MockitoRunner。

Mockito还提供了一条规则来克服无法使用MockitoJUnitRunner ,例如:

@Rule
public MockitoRule mockito = org.mockito.junit.MockitoJUnit.rule();

...或者您可以手动设置Mockito:

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

暂无
暂无

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

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