在 Spring Junit 5 测试中减少或删除 @Autowired 注释

Reduce amount of or remove @Autowired annotations In Spring Junit 5 test

在 Junit 5 中是否可以在没有 @Autowired 注释的情况下将 spring bean 注入到测试 class 中?我的代码如下所示:

@SpringBootTest(classes = SomeApp.class)
@ExtendWith(SpringExtension.class)
public class SomeTest {
    @Autowired
    private SomeService someService

    @Test
    public void shouldMakeMagic() { ....

我想删除所有@Autowired 注释

Kotlin 的优点是可以在构造函数中声明成员字段,而这在 Java 中是做不到的。在 Java 中,您可以制作 @Autowired 构造函数,但它不会减少样板,因为您仍然必须在 class.

中声明 class 成员

但是,如果您愿意使用神奇的 Java 样板代码删除程序 Project Lombok,您可以实现类似的效果,请参见下面的示例和注释:

@SpringBootTest
@ExtendWith(SpringExtension.class)
// Below will generate you the constuctor for each final member
// and add @Autowired on it so resulting:
// @Autowired
// public SomeTest(SomeService someService, SomeOtherService someOtherService)    
// {
//    this.someService = someServive;
//    this.someOtherService = someOtherServive;
// }
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class SomeTest {

    private final SomeService someService;
    private final SomeOtherService someOtherService;

    @Test
    public void shouldMakeMagic() {
        assertNotNull(someService);
        assertNotNull(someOtherService);
    }
    
}

现在的区别在于,Kotlin 会自动从构造函数生成成员,而 Java & Lombok 从成员生成构造函数。

注意:这当然也适用于主要代码,而不仅仅是测试。