【问题标题】:Inject custom service to spring boot test将自定义服务注入 Spring Boot 测试
【发布时间】:2021-05-04 06:36:24
【问题描述】:

我有一个接口 I 和 2 个以上的实现/服务(例如 I1I2

public interface I {

    void handle();
    Network getNetwork();
}

我还有另一项服务(例如 IHolder),它正在注入实现 I 的所有服务的列表,并将其放入其内部私有地图字段中key 是一些唯一的 Enum(接口具有返回一个的公共方法)并重视实现本身。

 public class IHolder {

    private final Map<Network, I> iByNetwork = new HashMap<>();

    public IHolder(List<I> is) {
        for (I i : is) {
            register(i.getNetwork(), i);
        }
    }

    private void register(Network network, I i) {
        this.iByNetwork.put(network, i);
    }

    public I getI(Network network) {
        return iByNetwork.get(network);
    }
}

现在我想将 IHolder 注入到我的测试类中,以使用他填充了这些服务的地图

【问题讨论】:

    标签: java spring spring-boot mockito


    【解决方案1】:

    所以基本上用@Service注释IHolder类,但你将无法使用它的private字段(地图),至少不是以简单的方式......

    编辑 尝试将这些注释添加到您的测试类中:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    

    【讨论】:

    • 已经注释了。我想在我的测试类中使用他的 getI(...) 方法,但它抛出 NPE bcs 构造函数注入不起作用。
    • @Autowired 怎么样?
    • 在常规 src 中它可以工作,但在我的测试中没有
    • 您的测试应该放在 /src 目录中!
    • 对不起,我的意思是main dir
    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2016-09-02
    • 2016-08-16
    • 1970-01-01
    • 2021-03-15
    • 2016-10-23
    相关资源
    最近更新 更多