1

I am writing a JUnit test case for my code, but the Mockito is always returning null

@Component
public class ConnectorImpl {

    public String returnString(String inte) {

        String x = testing();
        return x;
    }

    public String testing() {
        return "test";
    }
}

Test class

@RunWith(MockitoJUnitRunner.class)
public class ConnectorImplTest  {

    @Mock public ConnectorImpl connector;

    @Test
    public void testLoggedInRefill() throws Exception {

        Mockito.when(connector.testing()).thenReturn("test");


        String x = connector.returnString("8807");

        assertEquals("8807", x);
    }

}

When I am calling connector.returnString("8807");, it is always returning null. Is there anything I am doing wrong? I am new to JUnit.

Dmytro Chasovskyi
  • 3,209
  • 4
  • 40
  • 82
Prateek
  • 21
  • 1
  • 3
  • Possible duplicate of [Mockito - spy vs mock](https://stackoverflow.com/questions/28295625/mockito-spy-vs-mock) – Turing85 Dec 30 '18 at 14:07
  • tl;dr: you want a `Spy`, not a `Mock`. As an aside: instead of mocking `testing()`, you should mock the call to `returnString("8807");`(then you can keep using `Mock`s) – Turing85 Dec 30 '18 at 14:08

3 Answers3

0

One way you can test your method returnString is as :

// mock 'returnString' method call
Mockito.when(connector.returnString(anyString()).thenReturn("test"); 
// assert that you've mocked succesfully
assertEquals("test", connector.returnString("8807"));
Naman
  • 27,789
  • 26
  • 218
  • 353
0

According to your code, you are mocking your ConnectorImpl

So it is an empty object and it means that it is up to you to specifically when(...).then(...) any functionality that you like to test.

BTW - if you are testing the ConnectorImpl then you should not mock it, but actually use the real bean. You should mock the beans that ConnectorImpl is using.

So I would suggest your code look maybe like that:

@RunWith(MockitoJUnitRunner.class)
public class ConnectorImplTest  {

    public ConnectorImpl connector = new ConnectorImpl(...);

    @Test
    public void testLoggedInRefill() throws Exception {
        String x = connector.returnString("8807");
        assertEquals("8807", x);
    }
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
riorio
  • 6,500
  • 7
  • 47
  • 100
0

You are mocking the object and you do not specify any behaviour for the returnString method of the mocked object. As you did for testing(), you can do the same for returnString() method:

when(connector.returnString(anyString())).thenReturn("text")

On the other hand why do you need ti mock this class?

user1474111
  • 1,356
  • 3
  • 23
  • 47