Spring:具有field& amp的类的单元测试构造函数注入

时间:2017-03-27 11:37:32

标签: java spring unit-testing mockito autowired

我的课程设置如下。

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

我知道关于字段注入的所有争论都是邪恶的,但是我更有兴趣知道是否有办法解决这个问题而不改变BaseChild类注入其属性的方式? / p>

谢谢!

1 个答案:

答案 0 :(得分:3)

这样做:

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应该做正确的事。