【问题标题】:Why is my configuration test class not working?为什么我的配置测试类不起作用?
【发布时间】: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


    【解决方案1】:

    造成上述异常,当我们没有创建该类型的 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 {
    
       }
    }
    

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

    【讨论】:

    • 出于安全原因,我不得不更改类的名称。所以你能够用我的代码毫无问题地构建?我的经理也怀疑我的项目结构问题..
    • 是的,我运行代码它为我工作。 @Autowired 私人服务服务;在配置类中没有效果。因为 configure 类用于创建 bean,而不是你已经在使用它而不创建它。
    • 是的,我实际上删除了整个分支并重新编写了代码并且它起作用了。仍然不确定出了什么问题,但我会接受的:)
    猜你喜欢
    • 2012-07-20
    • 2018-07-19
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多