测试 spring-boot @service 类

And*_*rdi 5 java spring spring-mvc spring-test spring-boot

我想测试一个@Service通常用SpringApplication.run().

服务类是:

@Service
@EnableConfigurationProperties(AppProperties.class)
public class MongoService {

    private static final Logger logger = LoggerFactory.getLogger(MongoService.class);

    private MongoClient mongoClient;

    private final AppProperties properties;

    @Autowired
    public MongoService(AppProperties properties) {
        this.properties = properties;
    }

    /**
     * Open connection
     */
    public void openConnection() {

        try {
            mongoClient = new MongoClient(new MongoClientURI(properties.getMongoConnectionString()));
        } catch (Exception e) {
            logger.error("Cannot create connection to Search&Browse database", e);
            throw new BackendException("Cannot create connection to Search&Browse database");
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

当它通过启动与控制器叫SpringApplication.run()时,MongoService不为空,但是,当我从它不工作JUnit的尝试。

所以,我正在尝试这个:

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = AppProperties.class)
public class MongoServiceTest {

    private static final Logger logger = LoggerFactory.getLogger(MongoServiceTest.class);

    @Autowired
    MongoService mongoService;

    @Test
    public void MongoServiceAutowired() {   
        assertNotNull(mongoService);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到此异常:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“mypackage.MongoServiceTest”的bean时出错:通过字段“mongoService”表达的不满意依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“mypackage.services.mongo.MongoService”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

有什么线索吗?我哪里失败了?

Dan*_*aub 5

我假设您的AppPropertiesMongoService不在同一个包中

如果没有,您可以MongoService以这种方式注入:

创建另一个名为的类 TestConfiguration

@ComponentScan(basePackageClasses = {
        MongoService.class,
        AppProperties.class
})
@SpringBootApplication
public class TestConfiguration {
    public static void main(String[] args) {
        SpringApplication.run(TestConfiguration.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

在测试中只需更改为:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class) 
public class MongoServiceTest {

    private static final Logger logger = LoggerFactory.getLogger(MongoServiceTest.class);

    @Autowired
    MongoService mongoService;

    @Test
    public void MongoServiceAutowired() {   
        assertNotNull(mongoService);
    }
}
Run Code Online (Sandbox Code Playgroud)