首页 > 解决方案 > 错误模拟 @Inject 类 JUnit Mockito

问题描述

我在使用 JUnit 和 Mockito 时遇到了一些麻烦。首先,我给你我所拥有的所有信息。

JWTValidator.java

@Inject
JWTUtils jwtUtils;

public void validateJWT(String jwt) { //The main function returns true, false or an exception
[...]
Claims claims = jwtUtils.getClaims(jwt); //claims = null here!
[...]
}

JWTUtils.java

public void getClaims(jwt) { //This should return an Exception with the JWT that I use on the JWTTestServlet.java
[...]
}

JWTTestServlet.java

@InjectMocks
private JWTValidator jwtValidator;
        
@Mock
private JWTUtils jwtUtils;

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test(expected=Exception.class)
public void testJWTWithoutGUID() {
final String jwt = ""; //Some JWT 
    String message = "";
    try {
        jwtValidator.validateJWT(jwt);
    } catch (Exception e) {
        message = e.getMessage();
        System.out.println(message);
    }
    assertTrue(message.contains(MSG_WITHOUT_GUID));
}

关键是当我调用 JWTUtils 的getClaims函数时,它不起作用,我收到一个空字段。我尝试了许多不同的注释,但它也不起作用。JWTUtils 为 null 或函数返回 null。

我可以调试 JWTValidator,但不能调试 JWTUtils。

你能帮我么?

非常感谢你最好的问候

标签: javajunitmockingmockito

解决方案


解决了!解决方案是我必须定义模拟类的行为(JWTUtils)

when(jwtUtils.getJWTClaims(jwt)).thenReturn(new DefaultClaims());

现在,当我调用此函数时,我没有空对象。

非常感谢!


推荐阅读