为什么我的配置测试 class 不起作用?

Why is my configuration test class not working?

我正在尝试使用 junit 为我的服务配置编写单元测试 class。我有在其他模块中工作的现有代码,但由于某种原因它在这个模块上不起作用,我无法弄清楚。这是我的代码:

服务配置class:

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 class:

package service;

public class ServiceImpl implements Service {

    @Override
    public void search() throws Exception {
        return null;
    }
}

服务配置测试class:

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 和配置 class 方面没有太多经验。然而,这对我来说似乎是合法的,我基本上遵循了已经在其他模块中运行的代码。我的经理也找不到问题所在。

上面的异常是造成的,当我们没有创建该类型的bean时会抛出异常“Error creating bean with name 'className'.

我尝试了适用于我的相同代码。但是,您不需要创建Service Config来创建ServiceImpl的bean,只需使用@Service注解ServiceImpl,您就可以随后对其进行测试。

 @Service
 public class ServiceImpl implements Service {

 @Override
 public void search() throws Exception {

   }
}

并避免使用预定义名称(例如:服务)作为 class 名称。