gpt4 book ai didi

java - 带有新初始化类变量的 Mockito InjectMocks

转载 作者:行者123 更新时间:2023-11-30 02:09:49 27 4
gpt4 key购买 nike

这到底是如何运作的?按照我的理解,不应该有。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.

所以步骤是:

  1. AuthorizationHandler 已实例化
  2. 调用实例初始化程序
  3. 已创建 LDAPGroupAccessor 并将其分配给 groupAccessor
  4. @InjectMocks 运行并用 @Mock 替换分配给 groupAccessor 的实例

关于java - 带有新初始化类变量的 Mockito InjectMocks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50424048/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com