使用MockitoJUnitRunner时加载属性

时间:2018-11-14 09:04:10

标签: java spring spring-boot mockito

我正在尝试从服务单元测试中的application-test.properties加载属性值(使用MockitoJUnitRunner.class),但使用@Value注释总是获得空值。

@RunWith(MockitoJUnitRunner.class)
public class AlertQueryServiceImplTest {

@Value("${raw.path}")
private static String rawJson;

@InjectMocks
private AlertQueryServiceImpl alertQueryServiceImpl;

@Mock
private AlertCBDAOImpl alertCBDAOImpl;

private List<Alert> alertListExpected;

@Before
public void setUp() {
    ReflectionTestUtils.setField(alertQueryServiceImpl, "url", "http://someurl");
    alertListExpected = JsonUtils.
            loadObjectList(Alert.class, JsonUtils.ALERTS_FILE);
    assertFalse(alertListExpected.isEmpty());
}

@Test
public void shouldReturnAlerts() {
    User userTest = new User("108998", "3000747091");
    JsonDocument jsonDocExpected = JsonUtils.stringToJsonDocument(rawJson, userTest.getAssociatedBE());

    when(alertCBDAOImpl.getDoc(userTest.getAssociatedBE())).thenReturn(jsonDocExpected);
    when(alertCBDAOImpl.getAlerts(jsonDocExpected)).thenReturn(alertListExpected);
}
}

如何将raw.path属性加载到rawJson字段中?

1 个答案:

答案 0 :(得分:0)

首先,您需要设置活动配置文件以访问application-test.properties文件,您可以在测试类上使用@ActiveProfiles(“ test”)批注进行操作。 https://www.baeldung.com/spring-testing-separate-data-source 我认为@Value注释不能与static关键字一起使用。

相关问题