在下面的单元测试中,我手动提供属性并尝试从现有的 YAML 资源文件中读取它们(尝试了不同的策略)@TestPropertySource
), the @Value{..}
属性未设置,我总是为它们获取 NULL:
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
"eligible_filename = xyz"
})
@ExtendWith(MockitoExtension.class)
public class AppServiceTest {
@Value("${eligible_filename}") // This var is always NULL
也
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = "application-test.yaml") /* File exists, also tried resources/application-test.yaml */
@ExtendWith(MockitoExtension.class)
public class AppServiceTest {
@Value("${eligible_filename}") // This var is always NULL
这就是我最终决定的。我们must use @SpringBootTest
加载测试属性(application-test.yaml
)并得到@Value(..)
,但不幸的是这会导致整个应用程序运行。要屏蔽正在使用的真实对象并替换模拟对象,我们可以使用@SpringBootTest
with @Import(SomeConfiguration.class)
如下。这将使模拟对象在运行时被拾取@SpringBootTest
test:
@SpringBootTest
@Import(value = {MockAppServiceConfiguration.class,
MockEmailServiceConfiguration.class}) // etc. any other mocked objects
public class MyTest {
}
模拟服务配置示例:
public class MockEmailServiceConfiguration {
// Replace with mock EmailService when running full-application @SpringBootTest tests
@Bean
public EmailService emailService(){
return new EmailService() {
//... Override any service methods with a mock result (no real processing)
}
现在您可以运行测试,而无需连接真实的对象。但由于我们仍然需要对实际的服务类进行单元测试,因此我手动创建自己的 Service 对象并对其进行 Mockito 测试openMocks / @Mock / @InjectMocks)
。这是测试实际服务类的第 2 部分:
@SpringBootTest
@Import(value = {MockAr11ApplicationServiceConfiguration.class, /* Prevent the loading of the real Ar11ApplicationService during @SpringBootTest's full-application launch */
MockEmailServiceConfiguration.class}) /* Prevent the loading of the real EmailService during @SpringBootTest's full-application launch */
@ExtendWith(MockitoExtension.class)
public class Ar11ApplicationServiceTest {
// Custom object to be constructed for unit testing, includes DAO sub-object via InjectMocks
@InjectMocks
Ar11ApplicationServiceImpl ar11ApplicationServiceImpl;
// Custom DAO sub-object to be constructed for this unit test via Mock
@Mock
private Ar11ApplicationDAO ar11ApplicationDAO;
@BeforeEach
void setUp() throws Exception {
// Manually construct/wire my own custom objects for unit testing
ar11ApplicationServiceImpl = new Ar11ApplicationServiceImpl();
ar11ApplicationDAO = new Ar11ApplicationDAO();
ar11ApplicationServiceImpl.setAr11ApplicationDAO(ar11ApplicationDAO);
MockitoAnnotations.openMocks(this);
// Set up mock behaviors for the DAO sub-object with when/then
when(ar11ApplicationDAO.method(filename)).thenReturn(..)
doNothing().when(ar11ApplicationDAO).voidMethod(params);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)