Spring:对具有字段和构造函数注入的类进行单元测试

Mub*_*bin 4 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在为班级编写单元测试Child。如果我使用@InjectMocks,那么otherService结果将为空。Child如果我在测试设置中使用类的构造函数,则Base类中的字段将为null.

我知道关于字段注入是邪恶的所有争论,但我更感兴趣的是知道是否有一种方法可以在不改变类注入其属性的方式Base和方式的情况下解决这个问题Child

谢谢!!

joh*_*384 7

只需这样做:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mockito 应该做正确的事。