【发布时间】:2020-06-23 16:41:40
【问题描述】:
我正在尝试使用 junit 为我的服务配置类编写单元测试。我有在其他模块中工作的现有代码,但由于某种原因它在这个模块上不起作用,我无法弄清楚。这是我的代码:
ServiceConfig 类:
package config.service;
import service.Service;
import service.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServiceConfig {
@Autowired
private Service service;
@Bean
public Service service() {
return new serviceImpl();
}
}
服务接口:
package service;
public interface Service {
void search() throws Exception;
}
ServiceImpl 类:
package service;
public class ServiceImpl implements Service {
@Override
public void search() throws Exception {
return null;
}
}
ServiceConfigTest 类:
package config.service;
import service.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { ServiceConfig.class })
public class ServiceConfigTest {
@Autowired
private Service service;
@Test
public void service() {
assertNotNull(service);
}
}
这里是例外:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ServiceConfig': Unsatisfied dependency expressed through field 'Service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.nuance.powershare.dispatchreporter.service.Service' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我对 spring 和配置类没有太多经验。但是,这对我来说似乎是合法的,我基本上遵循了已经在其他模块中工作的代码。我的经理也找不到问题所在。
【问题讨论】:
标签: spring unit-testing junit javabeans