Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito thenReturn returns null when coming from generic function

I want to mock the ResultSet in a class, whose parameters come from a generic return function (getSQLValue):

public class MyClass{

    TableClass clsTableClass;

    public void getResults(Integer index, Integer value, String str) throws SQLException {

        try (ResultSet rsResult = clsTableClass.getRecords(
                getSQLValue(index, value, -1),
                getSQLValue(index, str, "")))
        {
            // do stuff
        }
    }

    private <T> T getSQLValue(Integer index, T t, T def) {
        return (index> 0) ? def : t;
    }
}

The table class with the signature method:

public class TableClass {

    public ResultSet getRecords(Integer value, String str)  {
        // do stuff
    }

And this is the unit test class:

public class MyClassTest {

    @Mock(name = "clsTableClass")
    TableClass clsTableClass;
    @InjectMocks
    MyClass clsMyClass;

    @Before
    public void setUp() throws Exception
    {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testClass() throws Exception
    {
        ResultSet rsResult = Mockito.mock(ResultSet.class);

        when( clsTableClass.getRecords(
                any(Integer.class),
                any(String.class)).thenReturn(rsResult);
    }
}

The problem is that the ResultSet is always null, I can confirm when debugging.

like image 280
Henrique de Sousa Avatar asked Dec 23 '22 10:12

Henrique de Sousa


1 Answers

Turns out that Mockito, after "accepting" the first argument as Integer, fails to aceppt the second argument as String. The solution (after much debugging) is to cast the any() matcher in the test function to the corresponding class type:

@Test
public void testClass() throws Exception
{
    ResultSet rsResult = Mockito.mock(ResultSet.class);

    when(clsTableClass.getRecords(
            (Integer) any(),
            (String) any()).thenReturn(rsResult);
}

Now Mockito will match the parameters and the ResultSet will no longer return null.

like image 170
Henrique de Sousa Avatar answered Jan 11 '23 23:01

Henrique de Sousa