001package io.avaje.inject.core; 002 003import org.mockito.Mockito; 004 005import java.util.function.Consumer; 006 007/** 008 * Holds beans supplied to the dependency injection. 009 * <p> 010 * These are typically test doubles or mock instances that we supply in testing. 011 * When we supply bean instances they take precedence over other beans that 012 * would normally be injected. 013 * </p> 014 */ 015public class SuppliedBean<B> { 016 017 private final Class<B> type; 018 019 private final Consumer<B> consumer; 020 021 private B bean; 022 023 /** 024 * Create with a given target type and bean instance. 025 */ 026 public SuppliedBean(Class<B> type, B bean) { 027 this(type, bean, null); 028 } 029 030 /** 031 * Create with a consumer to setup the mock. 032 */ 033 public SuppliedBean(Class<B> type, B bean, Consumer<B> consumer) { 034 this.type = type; 035 this.bean = bean; 036 this.consumer = consumer; 037 } 038 039 /** 040 * Return the dependency injection target type. 041 */ 042 public Class<B> getType() { 043 return type; 044 } 045 046 /** 047 * Return the bean instance to use (often a test double or mock). 048 */ 049 public B getBean() { 050 if (bean == null) { 051 // should extract a SPI for this 052 bean = Mockito.mock(type); 053 } 054 if (consumer != null) { 055 consumer.accept(bean); 056 } 057 return bean; 058 } 059}