我可以使用 Autowired 构造函数将模拟注入到原型 bean 中吗?

Can I inject mocks into a prototype bean with Autowired constructor?

是否可以使用 @Autowired 构造函数将模拟服务注入原型 bean?我意识到我可以切换到 setter 注入,但如果可能的话我更愿意使用构造函数。

@Component
@Scope(value = "prototype")
public class Prototype {

    private DependantService dependantService;

    @Autowired
    public Prototype(DependantService dependantService) {
        this.dependantService = dependantService;
    }
}
@SpringBootTest
public class TestPrototype {

    @Autowired
    private ApplicationContext ctx;

    @Mock
    private DependantService dependantService;

    @Test
    public void testPrototype() {
        // How can I inject the mock service?
        ctx.getBean(Prototype.class);
    }
}

原来有一个接受参数的 getBean 方法的重载版本。如果可以的话,我会否决我的问题。

@SpringBootTest
public class TestPrototype {

    @Autowired
    private ApplicationContext ctx;

    @Mock
    private DependantService dependantService;

    @Test
    public void testPrototype() {
        Prototype p = ctx.getBean(Prototype.class, dependantService);
        // Test p
    }
}

如果您想加快单元测试,[并进行 true 独立单元测试,]我建议您查看 @InjectMocks mockito 注释。 @SpringBootTest 启动非常笨重的 Spring 容器。

@Controller
public class MyController {
 @Inject
 private Logger log;


 public methodThatNeedsTesting(){
  log.info("hey this was called");
 }
}
@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith({ MockitoExtension.class })
class MyControllerTest {
 @Mock
 private Logger log;

 @InjectMocks
 private MyController myController;
 
 @Test
 void test_methodThatNeedsTesting() throws Exception {
  myController.methodThatNeedsTesting();
  // myController will not throw an NPE above because the log field has been injected with a mock
 }