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

标签 java spring unit-testing dependency-injection mockito

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

相关文章:

Java SpringMVC 异常时的错误对象

java - android studio 需要很多时间来打开项目?

java - 使用 Glide 使用 foreach 循环显示多个图像

java - 带有方面参数的注释

java - @JoinColumn 注解中名称和引用列名的区别?

python - unittest 的tearDown 和setUp 不会以相同的方式更新属性

PHPUnit 没有捕捉到预期的异常

c# - 如何对返回 void 的方法进行单元测试?

java - Android使一个元素只出现在纵向 View 中

java - 如何在 Spring Integration java dsl 中创建 header 值路由器并为其分配默认输出 channel ?