首页 > 解决方案 > 如何在 Spring Boot 中使用 @ConfigurationProperties 模拟类

问题描述

我有一个使用@ConfigurationProperties 自动连接另一个类的类。

带有@ConfigurationProperties 的类

@ConfigurationProperties(prefix = "report")
public class SomeProperties {
    private String property1;
    private String property2;
...

Autowires 类 SomeProperties 之上的类

@Service
@Transactional
public class SomeService {
    ....
    @Autowired
    private SomeProperties someProperties;
    .... // There are other things

现在,我想测试SomeService类,在我的测试类中,当我模拟SomeProperties类时,我得到null了所有属性的值。

测试班

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SomeProperties.class)
@ActiveProfiles("test")
@EnableConfigurationProperties
public class SomeServiceTest {
    @InjectMocks
    private SomeService someService;

    @Mock // I tried @MockBean as well, it did not work
    private SomeProperties someProperties;

如何模拟具有文件属性的SomePropertiesapplication-test.properties

标签: javaspring-bootmockingmockitospringmockito

解决方案


如果您打算绑定属性文件中的值,则不是在模拟 SomeProperties,在这种情况下,将提供 SomeProperties 的实际实例。

嘲笑:

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {

    @InjectMocks
    private SomeService someService;

    @Mock
    private SomeProperties someProperties;

    @Test
    public void foo() {
        // you need to provide a return behavior whenever someProperties methods/props are invoked in someService
        when(someProperties.getProperty1()).thenReturn(...)
    }

No Mock(someProperties是一个真实的对象,它从某个属性源绑定它的值):

@RunWith(SpringRunner.class)
@EnableConfigurationProperties(SomeConfig.class)
@TestPropertySource("classpath:application-test.properties")
public class SomeServiceTest {
   
    private SomeService someService;

    @Autowired
    private SomeProperties someProperties;

    @Before
    public void setup() {
        someService = new someService(someProperties); // Constructor Injection
    }
    ...

推荐阅读