我在Maven项目中有此配置类:
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;
}
和其他班级
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
为空
您应该使用弹簧流道来运行测试用例,以便可以注入弹簧豆。
@RunWith(SpringJUnit4ClassRunner.class)