如何解决如何在Spring Boot中使用@ConfigurationProperties模拟类 具有@ConfigurationProperties的类可以自动装配SomeProperties类之上的类测试类
我有一个可以使用@ConfigurationProperties自动装配另一个类的类。
具有@ConfigurationProperties的类
@ConfigurationProperties(prefix = "report")
public class SomeProperties {
private String property1;
private String property2;
...
可以自动装配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;
如何模拟具有来自application-test.properties
文件的属性的 SomeProperties 。
解决方法
如果使用@Mock,则还需要对值进行存根。默认情况下,所有属性的值为空。
,您需要对SomeServiceTest.java的@ Test / @ Before方法中的所有属性值进行存根,例如:
ReflectionTestUtils.setField(someProperties,"property1","value1");
ReflectionTestUtils.setField(object,name,value);
您还可以通过Mockito.when()
模拟对依赖类的响应 ,如果要绑定属性文件中的值,则不会嘲笑SomeProperty,在这种情况下,将提供SomeProperty的实际实例。
模拟:
@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(...)
}
没有模拟(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
}
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。