运行 测试时,ContextConfiguration 不注入配置文件

ContextConfiguration does not inject config file when running the Test

我在一个maven项目中有这样的配置class:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import lombok.Data;

@Data
@Configuration
public class SmsConfig {

    @Value("${sms.domainId}")
    private String domainId;

    @Value("${sms.gateway.url}")
    private String gatewayUrl;

    @Value("${sms.cmd}")
    private String cmd;

    @Value("${sms.login}")
    private String login;

    @Value("${sms.passwd}")
    private String passwd;

}

和另一个 class

Service("smsService")
public class AltiriaSMSRestServiceImpl implements SmsService {

    private final SmsConfig smsConfig;

    public AltiriaSMSRestServiceImpl(SmsConfig smsConfig) {
        this.smsConfig = smsConfig;
    }

    @Override
    public boolean sendSMS(String msg, String to) throws Exception {
    ...
    }
...
}

我想使用这个文件进行测试:

@ContextConfiguration(classes = { SmsConfig.class })
@RunWith(MockitoJUnitRunner.class)
public class AltiriaSMSRestServiceImplTest {

    @InjectMocks
    private AltiriaSMSRestServiceImpl smsService;

    @Test
    public void testSendSMS() throws Exception {
        smsService.sendSMS("this is a test", "+34653776498");
    }

}

但是我有一个 nullpointerException 因为当 运行 测试

smsConfig 为空

您应该使用 spring 运行ner 到 运行 测试用例,以便可以注入 spring 个 bean。

@RunWith(SpringJUnit4ClassRunner.class)