0

I'm new to unit tests, and I'm having trouble covering a line trying to get in the tests, follow the code and the line it couldn't cover.

enter image description here

Code:

public void setKey(String myKey) {

   MessageDigest sha = null;
   try {
      key = myKey.getBytes("UTF-8");
      sha = MessageDigest.getInstance("SHA-256");
      key = sha.digest(key);
      key = Arrays.copyOf(key, 16); // use only first 128 bit
      secretKey = new SecretKeySpec(key, "AES");
   }  catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
      logger.error("Error while Set Key:", e);
   }
}
  • Do not include links to images in your question. Instead include code and add a note on the line that is not covered. – DwB Oct 28 '22 at 16:09
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 28 '22 at 17:19
  • Hey @AntonioXavierdeSousaNeto , was my answer helpful? If so I would appreciate if you marked it as correct! – mrkachariker Nov 08 '22 at 11:16

1 Answers1

0

You would need to provide a test covering the scenario that one of the exceptions is thrown, therefore executing the code inside your catch block. The exception UnsupportedEncodingException can be thrown by the following line:

key = myKey.getBytes("UTF-8");

To do that, generally in unit testing, you can use a library which enables you to do mocking, Mockito being one of the most popular ones.

So, once you check out these resources above, what you have to do is mock one (or both) of the lines that can throw the exceptions and make them throw the actual exceptions, and then, expect the line logger.error("Error while Set Key:", e); to be executed.

You can either check for the logging to happen, or use Mockito again to verify that the error() method has been called. Happy coding! =)

mrkachariker
  • 411
  • 4
  • 9