2

我有一个使用@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

4

3 回答 3

1

如果您打算绑定属性文件中的值,则不是在模拟 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
    }
    ...
于 2020-09-11T20:27:27.030 回答
0

如果您使用的是 @Mock ,则还需要存根这些值。默认情况下,所有属性的值为 null。

于 2020-09-11T14:54:53.680 回答
0

您需要在 SomeServiceTest.java 的 @Test/@Before 方法中存根所有属性值,例如:

ReflectionTestUtils.setField(someProperties, "property1", "value1");

ReflectionTestUtils.setField(object, name, value);

                         

您还可以通过 Mockito.when() 模拟依赖类的响应

于 2020-09-11T17:11:45.237 回答