在Spring应用程序中运行Junit测试时的不满意依赖性

时间:2019-11-23 11:57:13

标签: java spring spring-mvc junit integration-testing

我在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;

}

我在Spring项目中有这个服务类:

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(SpringJUnit4ClassRunner.class)
public class AltiriaSMSRestServiceImplTest {

    @Autowired
    @Qualifier("smsService")
    private AltiriaSMSRestServiceImpl smsService;

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

}

但是运行测试时出现此错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.bonanza.service.AltiriaSMSRestServiceImplTest': Unsatisfied dependency expressed through field 'smsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.bonanza.service.AltiriaSMSRestServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value="smsService")}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)

2 个答案:

答案 0 :(得分:0)

您在上下文配置中缺少AltiriaSMSRestServiceImpl类。在您的上下文配置中指定AltiriaSMSRestServiceImpl类,然后它应该可以工作。

答案 1 :(得分:0)

我认为您在混淆Spring配置和配置属性。

ij> values SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.locks.escalationThreshold');
1
--------------------------------------------------------------------------------------------------------------------------------
5000

1 row selected