春季:单元测试同时具有字段&构造函数注入 [英] Spring: unit test for class that has both field & constructor injection

查看:57
本文介绍了春季:单元测试同时具有字段&构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面设置了课程.

class Base {
   @Autowired
   private BaseService service; //No getters & setters
   ....
}

@Component
class Child extends Base {
  private final SomeOtherService otherService;

  @Autowired   
  Child(SomeOtherService otherService) {
     this.otherService = otherService;
  }
}

我正在为 Child 类编写单元测试.如果我使用 @InjectMocks ,则 otherService 会为空.如果使用测试设置中的 Child 类的构造函数,则 Base 类中的字段显示为 null .

I am writing a unit test for the Child class. If I use @InjectMocks then the otherService comes out to be null. If I use, the constructor of Child class in the setup of the test, then the fields in Base class comes out to be null.

我知道关于字段注入的所有争论都是邪恶的,但是我更想知道是否有一种方法可以解决此问题,而无需更改 Base Child 的方式类注入其属性?

I know all the arguments about field injection being evil, but I am more interested in knowing if there is a way to solve this without changing the way Base and Child classes injects their properties?

谢谢!

推荐答案

只需执行以下操作:

public class Test {
    // Create a mock early on, so we can use it for the constructor:
    OtherService otherService = Mockito.mock(OtherService.class);

    // A mock for base service, mockito can create this:
    @Mock BaseService baseService;

    // Create the Child class ourselves with the mock, and
    // the combination of @InjectMocks and @Spy tells mockito to
    // inject the result, but not create it itself.
    @InjectMocks @Spy Child child = new Child(otherService);

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
    }
}

Mockito应该做正确的事.

Mockito should do the right thing.

这篇关于春季:单元测试同时具有字段&构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆