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 - Spring 错误 - 找不到处理程序方法

java - 我可以将组合框添加到 JTable 的特定单元格中吗?

java - 如何在 IDEA 中使用类路径而不是模块路径运行 Java 9 应用程序?

java - Entitymanager.persist 在 Informix UDR 中失败

java - 如何将数据从 HTML 传输到 Spring Controller

spring - 如何使用eureka、zuul服务器在tomcat中部署不同的spring boot微服务?

javascript - 关于我非常简单的购物车的 TDD/单元测试建议

使用 Py.Test 进行单元测试的 Python Mocking

c++ - Qt 中的 GMock 和 undefined reference 错误

c# - 如何注释java/c#代码