java - 错误模拟 @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。
你能帮我么?
非常感谢你最好的问候
解决方案
解决了!解决方案是我必须定义模拟类的行为(JWTUtils)
when(jwtUtils.getJWTClaims(jwt)).thenReturn(new DefaultClaims());
现在,当我调用此函数时,我没有空对象。
非常感谢!
推荐阅读
- php - 需要执行 composer 和 npm 的 WordPress 插件的集成测试
- javascript - 无法在 addEventListener 函数之外获取视频持续时间
- javascript - Observable 将多个函数调用组合成一个 Observable
- powershell - 使用 Powershell 获取网站权限
- c# - RegAsm 无法从另一个目录加载依赖项
- python - IndentationError:注释后出现意外缩进
- angularjs - 找不到角度服务
- ios - 在 AppDelegate 中设置 barButtonItem
- c# - c# Regex.Match 与 .Net Regex Tester 结果不匹配
- scala - 如何改进这个功能?