[英]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. 我是使用Java中的Mockito进行junit测试的新手。 I have been stuck at one point.
我被困在某一点上。 I have one abstract class AbstractA which needs to test.
我有一个抽象类AbstractA需要测试。 Implementation of AbstractA as below.
实现AbstractA如下。
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 上面的测试类是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(); 运行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. 您不需要测试抽象类tdd对抽象类一无所知,使其成为普通类,只有两个或多个类具有相同的代码重复,才能将其提升为抽象,对该类的测试不会改变。 Specify sql query string and IPRowMapper as constructor parameters this simplify and make your code more clean.
将sql查询字符串和IPRowMapper指定为构造函数参数,这可以简化代码并使代码更简洁。 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. 其次,您不需要为测试进行如此复杂的设置,只需要验证交互,不返回值,仅验证
NamedParameterJdbcTemplate
模拟,以及传递给它的值是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.