这到底是如何运作的? 按照我的理解,不应该有。 LDAPGroupAccessor 正在类中进行 new 初始化,或者可以在构造函数本身中进行 new 初始化,它没有被注入(inject),不是构造函数参数,也不是 spring bean 注入(inject)。
我知道可以使用反射,但是injectMocks如何注入(inject)它?这不是违背了 DI 的目的吗?
@Component
public class AuthorizationHandler {
private LDAPGroupAccessor groupAccessor = new LDAPGroupAccessor();
public isUserAuthorized(String userId, String groupId){
return groupAccessor.isUserInGroup(userId, ldapGroup);
}
}
public class AuthorizationHandlerTest {
@InjectMocks
private AuthorizationHandler authorizationHandler;
@Mock
private LDAPGroupAccessor groupAccessor = new LDAPGroupAccessor();
@Before
public void setup() {
String authorizedUser = "authorizedUser";
Mockito.when(groupAccessor.isUserInGroup("authorizedUser", "someGroup")).thenReturn(true);
}
@Test
public void test1() {
Assert.assertEquals(true, authorizationHandler.isUserAuthorized("authorizedUser", "someGroup"));
}
}
最佳答案
它只是使用 field injection 。来自 the documentation
Field injection; mocks will first be resolved by type (if a single type match injection will happen regardless of the name), then, if there is several property of the same type, by the match of the field name and the mock name.
所以步骤是:
AuthorizationHandler
已实例化- 调用实例初始化程序
- 已创建
LDAPGroupAccessor
并将其分配给groupAccessor
@InjectMocks
运行并用@Mock
替换分配给groupAccessor
的实例
关于java - 带有新初始化类变量的 Mockito InjectMocks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50424048/