简体   繁体   中英

How to deal with test class who is having dependency on abstract method using junit mockito in java

I am new to junit testing using mockito in java. I have been stuck at one point. I have one abstract class AbstractA which needs to test. Implementation of AbstractA as below.

public abstract class AbstractA implements ADao {
    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;
    @Override
    public List<String> getColumns(Set<String> ids) {
        String sql = query();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("ids", ids);
        return jdbcTemplate.query(sql, paramMap, rowMapper());
    }
    abstract protected String query();
    abstract protected AbstractIpRowMapper rowMapper();
}

And a test class for above is AbsractATest

public class AbsractATest {
    @InjectMocks 
    AbsractA abstractA;
    @Mock
    NamedParameterJdbcTemplate jdbcTemplate;

    @Mock AbstractIpRowMapper abstractIpRowMapper;
    @Before
    public void setUp() throws IOException, SQLException {
        abstractA=Mockito.mock(AbsractA.class, Mockito.CALLS_REAL_METHODS);
        jdbcTemplate=mock(NamedParameterJdbcTemplate.class);

        List<String> idsinput=new ArrayList<String>();
        idsinput.add("123");
        idsinput.add("124");
        idsinput.add("125");

        Set<String> ids=new LinkedHashSet<String>();
        ids.add("123");
        ids.add("124");
        ids.add("125");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("ids", ids);

        String query="select ids from tableA where ids=:ids";
        when(abstractA.query()).thenReturn(query);
        when(jdbcTemplate.query(query, paramMap,rowMapper())).thenReturn(idsinput);
        org.springframework.test.util.ReflectionTestUtils.setField(abstractA, "jdbcTemplate", jdbcTemplate);
    }

protected AbstractIpRowMapper rowMapper() {
    return absractIpRowmapper;
}
But after running this test case I am getting empty value for 
abstractA.getColumns();

Please help me to understand what I should need to do in above case.

Run doCallRealMethod().when(abstractA).getColumns(); in the unit test

You don't need to test abstract class tdd knows nothing about abstract classes, make it normal class and only you have same code duplication with two or more class lift it up to abstract, test for this class will not change. Specify sql query string and IPRowMapper as constructor parameters this simplify and make your code more clean. Second, you don't need such complicated setup for tests, you need only to verify interactions, not return value, verify only NamedParameterJdbcTemplate mock, whats values passed to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM