Skip to content
Advertisement

Condition fails in Junit5 & Mockito

I am trying to write the test case for my application and I cannot get past a condition even after providing what is expected, from what I know.

Here is my test class.

JavaScript

My implementation. The test doesn’t go past the if condition. The test does not cover the code after the condition as it turns true all the time. I need my test to cover keyMap() in the last line.

JavaScript

Can anyone please tell me how to correct this please? Using SpringBoot/JUnit 5

Advertisement

Answer

We discussed this in the comments, but in any case, I guess an example is better.

One way you could go about this is to make sure the same folder exists. In the test setup you could simply create it.

JavaScript

Now when accessing it in the implementation there will be a directory. You can also inside the test add files to the directory, so it’s not empty.

Although this works, it has some issues with setting it up and cleaning it up. A better way is to abstract this from the implementation itself and use some kind of provider for it.

A suggestion would be to create an interface where the real implementation returns the real folder and in tests you can mock this.

JavaScript

you can now make the getData class depend on this abstraction. You didn’t give us the class name, so don’t pay attention to that part:

JavaScript

Now during the test you can just inject your mocked directory/temp dir.

JavaScript

You can also add files to the temp dir if you need. This however should be enough to pass the if I think.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement