我正在为电子邮件DAO层编写一个测试用例。就像这样:
@Repository
@PropertySource({ "classpath:/query.properties" })
public class DaoLayerImpl implements DaoLayerDao {
/** The jdbc template. */
@Qualifier("mariaJdbcTemplate")
@Autowired
private JdbcTemplate jdbcTemplate;
/** The find staged query. */
@Value("${someQuery}")
String someQuery;
@Override
public List<SomeBean> getData() throws MariaDbException {
List<SomeBean> listOfData = new ArrayList<>();
try {
listOfData = jdbcTemplate.query(someQuery,
new BeanPropertyRowMapper<SomeBean>(SomeBean.class));
} catch (RuntimeException e) {
logger.error("RuntimeException in ", e);
}
return listOfData;
}
}
此层的测试用例是:
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@PropertySource("classpath:application-test.properties")
public class EmailDaoLayerTest {
@MockBean
JdbcTemplate jdbcTemplate;
@InjectMocks
DaoLayerImpl dao;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
jdbcTemplate = Mockito.mock(JdbcTemplate.someQuery);
ReflectionTestUtils.setField(dao, "jdbcTemplate", jdbcTemplate);
}
@Test
public void testCaseForGetData() throws Exception {
List<SomeBean> beanObject = new ArrayList<>();
beanObject.add(new SomeBean());
beanObject.add(new SomeBean());
beanObject.add(new SomeBean());
System.out.println(beanObject.size()); // 3
when(jdbcTemplate.query("someQuery",
new BeanPropertyRowMapper<SomeBean>(SomeBean.class))).thenReturn(beanObject);
List<SomeBean> obj = dao.getData();
System.out.println(obj.size()); //0
System.out.println("Done");
}
}
[嘲笑之后,对象的大小变为0而不是3。返回之前,对象的大小为3。当我实际命中DAO时,对象的大小变为0,而我已经嘲笑了使用when-then的jdbc模板。
模拟Bean属性行映射器类的正确方法是什么?
让我回答问题,然后批评您的方法,也许它将有助于更好地了解解决方案的最终外观。
所以回答您的问题:
从技术上讲,您可能可以做类似的事情:
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.any;
...
Mockito.when(jdbcTemplate.query(eq("someQuery"),
any(BeanPropertyRowMapper.class)).thenReturn(....);
但是,您应该问自己,您到底想在这里进行什么测试?您在这里有一个相对昂贵的集成测试,该测试运行Spring Context(与SpringRunner一起使用)并在后台创建许多对象。
但是基于要测试的方法-我看不到要测试的任何“有意义”(受测试限制)代码。您可以测试给定查询,BeanPropertyRowMapper确实可以将响应转换为SomeBean
的实例,但是随后您再次对其进行模拟,并且它实际上没有运行。
您可以检查已准备好的查询是否针对数据库运行并返回预期结果,但似乎您没有在此处准备任何数据库。
因此,如果目的是覆盖范围,那么您将被覆盖,但是测试不是关于覆盖范围,而是关于使您“确保”您的代码正常运行。在这种情况下,运行Spring Driven集成测试(带有应用程序上下文和所有内容)似乎是一个巨大的矫over过正,MockitoRunner
可以胜任]