0

I am new to java, So I created this class which return if the key is present in map, and if does, it should return the value of the key, but when I testing the code using mockito its not returning the expected. My method

private static Map<String,Long> map1= new HashMap<>();
    public long foo(final String test){
         if(!map1.containsKey(test)){
             return 0L;
         }
         return map1.get(test);
     }

And its test method is

private static Map<String,Long> map1 = mock(Map.class); 
 @Test
 public void testfoo(){
     when(map1.containsKey("test")).thenReturn(true);
     when(map1.get("test")).thenReturn(2L);
     long value = classUndertest.foo("test");
     Assert.assertEquals(2L, value);
 }

But the value I am getting is 0L.

Web Nerd
  • 5
  • 4
  • 1
    You're not injecting the mocked object into your tested object, you’re using a separately created one, see: https://stackoverflow.com/a/73741030/3305737 – Jonasz Sep 22 '22 at 13:17
  • Actually I am quite new to java, not understanding the whole of that, would you mind helping me with giving the example of this code. – Web Nerd Sep 22 '22 at 13:25
  • 2
    1.Why mocking a `java.util.HashMap`? (Just use a real one (..and put("test", 2L) inside!?:) 2. And if really have to (mock), then ensure the "field" ("map1" of "classundertest") is properly injected.. (for which you need powermock(before mockito 3.4) ..f.m.knowl "how to mock private/static fields") – xerx593 Sep 22 '22 at 13:28
  • @xerx593 if you go through this https://stackoverflow.com/questions/73817517/how-to-mock-hashmap-methods-using-mockito he has the same problem, if you can reply on that or here why it is not working, I think he is using what you tell exactly – Web Nerd Sep 22 '22 at 16:44
  • Does this answer your question? [Not able to inject Map into the object while testing with Mockito](https://stackoverflow.com/questions/73817517/not-able-to-inject-map-into-the-object-while-testing-with-mockito) (99% identical code) – knittl Sep 26 '22 at 06:12

0 Answers0