使用Spring JdbcTemplate的SimpleJdbcCall的Mockito [英] Mockito for SimpleJdbcCall with Spring JdbcTemplate

查看:127
本文介绍了使用Spring JdbcTemplate的SimpleJdbcCall的Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Junit测试用例中尝试了多种执行存储过程的方法,以针对out值进行测试,但是不幸的是,没有任何工作.我的测试用例:

I tried multiple way to execute the store procedure in my Junit test case to test against the out values but unfortunately nothing is working. My Test case:

public class DataTest {

    @Mock
    private static DataSource ds;

    @InjectMocks
    private DataDaoImpl dataDao = new DataDaoImpl();

    @Mock
    private static JdbcTemplate jdbcTemplate;

    @Mock
    private static SimpleJdbcCall viewProc;


    @Before
    public void setUp() throws IOException, InterruptedException {
        MockitoAnnotations.initMocks(this);
        MockMvcBuilders.standaloneSetup(dataDao).build();
    }

    @BeforeClass
    public static void init() throws Exception {
        viewProc = new SimpleJdbcCall(ds).withSchemaName("schema")
                .withProcedureName("viewProc").withoutProcedureColumnMetaDataAccess()
                .declareParameters(new SqlParameter("param1", Types.VARCHAR))
                .declareParameters(new SqlParameter("param2", Types.VARCHAR))
                .returningResultSet("dataModules", Mockito.anyObject());

        jdbcTemplate = new JdbcTemplate(ds);

    }

    @Test
    public void findDataModules() throws Exception {

        String param1 = "abc";
        List<DataObj> md = new ArrayList<DataObj>();


        int size = 3;
        SqlParameterSource in = new MapSqlParameterSource().addValue("param1", "abc").addValue("param2",
                "123");
        Map map = viewProc.execute(in);
        md = (List<DataObj>) map.get("data");
        assertTrue("Expected Data  ", md.size() >= size);


    }

}

我的主班:

@Repository
public class DataDaoImpl implements DataDao {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "db")
    private DataSource db;

    private SimpleJdbcCall viewProc;

    private JdbcTemplate jdbcTemplate;

    /**
     * Initialization of Stored Procs and JDBC Template
     * 
     * @throws Exception
     */
    @PostConstruct
    public void init() throws Exception {
        viewProc = new SimpleJdbcCall(db).withSchemaName("schema")
                .withProcedureName("viewProc").withoutProcedureColumnMetaDataAccess()
                .declareParameters(new SqlParameter("param1", Types.VARCHAR))
                .declareParameters(new SqlParameter("param2", Types.VARCHAR))
                .returningResultSet("data", new ViewDataRowMapper());

        jdbcTemplate = new JdbcTemplate(db);

    }

        @Override
    public List<Data> findUniqueDataModules(String p1, String p2) throws Exception {
        List<DataObj> dataModules = new ArrayList<DataObj>();
        try {
            SqlParameterSource in = new MapSqlParameterSource().addValue("param1", p1).addValue("param2",
                    p2);
            Map map = viewUniqueDataModulesByLicense.execute(in);
            dataModules = (List<DataObj>) map.get("data");
        } catch (Exception e) {
            //Hnadel Exception
        }
        return dataModules;
    }

    }

以上代码给出了异常,表明需要数据源.我尝试了Mockito,powerMockito,但它返回的是空地图.模拟也不例外.我可以通过我的测试用例的任何解决方案都可以.修改的命名.

Above code gives exception says datasource is required. I tried Mockito, powerMockito but it returning empty map. There is no exceptions with mock. I am OK with any solution which can pass my test case. Modified naming.

推荐答案

尽管我讨厌在测试中使用反射,但我相信它可以为您提供帮助.在这里,初始化后,将字段 viewProc 设置为可在测试中使用的模拟对象. @PostConstruct 是与Spring相关的注释,因此在初始化它时不会被调用.

As much as I hate using reflection in testing, I believe it can help you in your case. Here, after initializing, I set the field viewProc to a mock object which you can use in the test. @PostConstruct is a Spring related annotation, so it will not be called while initializing it.

class DataDaoImplTest {

    private DataDaoImpl dataDao;

    @Mock
    private DataSource dataSource;

    @Mock
    private SimpleJdbcCall jdbcCall;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);
        this.dataDao = new DataDaoImpl(dataSource);
        ReflectionTestUtils.setField(this.dataDao, "viewProc", jdbcCall);
    }

    @Test
    void findUniqueDataModules() throws Exception {
        // given:
        Map<String, Object> map = new HashMap<>();
        map.put("data", Arrays.asList(new DataDaoImpl.DataObj(), new DataDaoImpl.DataObj()));
        // mocks:
        when(jdbcCall.execute(any(SqlParameterSource.class))).thenReturn(map);
        // when:
        List<DataDaoImpl.DataObj> uniqueDataModules = this.dataDao.findUniqueDataModules("a", "b");
        // then:
        assertEquals(2, uniqueDataModules.size());
    }
}

另一种解决方案是针对测试数据库(例如H2)测试该方法.但这不会是单元测试.

Another solution would be to test the method against a test database, like H2. But it won't be a unit test.

这篇关于使用Spring JdbcTemplate的SimpleJdbcCall的Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆