简体   繁体   English

如何单独测试Util类依赖于其他Util类方法?

[英]How to Unit test Util class with dependency on other Util class method?

I have a util class which takes String jwtToken and Key key and decodes the jwt using io.jsonwebtoken.jwts. 我有一个util类,它接受String jwtToken和Key键,并使用io.jsonwebtoken.jwts对jwt进行解码。

However, I am not able to test this. 但是,我无法测试这一点。 The reason is, I am not able to mock the public key and pass to the method. 原因是,我无法模拟公钥并传递给方法。 So, the method breaks at Jwts.parser().serSigningKey(key)... 所以,该方法在Jwts.parser()断开.serSigningKey(key)......

I tried mocking the Public key but that too did not work as I am passing mock data to real function and get UnSupportedJwtException. 我尝试模拟公钥,但是这也没有用,因为我将模拟数据传递给实际函数并获取UnSupportedJwtException。

One way I can think of is to move the Util that converts String to Key into Util helper for test and use it and pass the converted key into the method. 我能想到的一种方法是将将String转换为Key的Util移动到Util辅助工具中进行测试并使用它并将转换后的密钥传递给方法。 This works however, I do not think it is the right way to approach the problem. 但这有效,我不认为这是解决问题的正确方法。

       Claims claims = null;

       try {
           claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwtToken).getBody();
       } catch (UnsupportedJwtException | MalformedJwtException | ExpiredJwtException
               | IllegalArgumentException ex) {
           LOGGER.error("Error in JWT/JWS validation", ex);
       }
       LOGGER.debug("Return Claims: ", claims);
       return claims;
   } ```

You can extract Jwts.parser() as separate field of your class instead of invoking this factory method directly in your method. 您可以将Jwts.parser()提取为类的单独字段,而不是直接在方法中调用此工厂方法。 Then you will be able to replace this object with mock 然后你就可以用mock替换这个对象了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM