模拟对象未返回预期值

huangapple go评论63阅读模式
英文:

Mocked Object not returning expected value

问题

我正在对我的 dao 进行单元测试我创建了一个列表往列表中添加了一个对象然后我告诉 mockito 当调用我的方法时返回一个带有单个对象的列表然而当我查看从 dao 方法返回的内容时得到的却是一个空列表我不确定我漏掉了什么

@InjectMocks
private Dao dao;

@Mock
private JdbcTemplate jdbcTemp;

@Test
public void testGetData() {
    List<MyObj> list = new ArrayList<>();
    MyObj myObj = new MyObj();
    myObj.setMethod("method val");
    list.add(myObj);

    Mockito.when(jdbcTemp.query(anyString(), Mockito.any(PreparedStatementSetter.class),
            Mockito.any(Dao.MyRowMapper.class))).thenReturn(list);

    List<MyObj> res = dao.getData(param1, param2); // 这是空的,而不是一个值为 1 的列表

    Assertions.assertThat(res).isNotNull();
}

我的 Dao 类:

public List<MyObj> getData(String arg1, String arg2) {
    List<MyObj> list = new ArrayList<MyObj>();

    try {

        list.addAll(jdbcTemp.query(query, new PreparedStatementSetter() {
            public void setValues(PreparedStatement pstmt) throws SQLException {
                pstmt.setString(PARAM_ONE, arg1);
                pstmt.setString(PARAM_TWO, arg2);
            }
        }, new MyRowMapper()));
    } catch (Exception exp) {

    }

    return list;
}
英文:

I'm unit testing my dao. I create a list, I add an object to my list and I tell mockito when my method is called, to return my list with a single object. However, when I look at what's returned from my dao method, it's an empty list. I'm not sure what I'm missing.

@InjectMocks
private Dao dao;
@Mock
private JdbcTemplate jdbcTemp;
@Test
public void testGetData() {
List&lt;MyObj&gt; list = new ArrayList&lt;&gt;();
MyObj myObj = new MyObj();
myObj.setMethod(&quot;method val&quot;);
list.add(myobj);
Mockito.when(jdbcTemp.query(anyString(), Mockito.any(PreparedStatementSetter.class),
Mockito.any(Dao.MyRowMapper.class))).thenReturn(list);
List&lt;MyObj&gt; res = dao.getData(param1, param2); // this is empty, instead of having a value of 1
Assertions.assertThat(res).isNotNull();
}

My Dao class:

public List&lt;MyObj&gt; getData(String arg1, String arg2) {
List&lt;MyObj&gt; list = new ArrayList&lt;MyObj&gt;();
try {
list.addAll(jdbcTemp.query(query, new PreparedStatementSetter() {
public void setValues(PreparedStatement pstmt) throws SQLException {
pstmt.setString(PARAM_ONE, arg1);
pstmt.setString(PARAM_TWO, arg2);
}
}, new MyRowMapper()));
} catch (Exception exp) {
}
return list;
}

答案1

得分: 1

我在描述问题时实际上犯了一个错误。

我的 dao 中有两个 jdbcTemplates。

所以我解决的方法是在创建模拟 jdbctemplate 时使用 @Qualifier("jdbcTemplate")

英文:

I actually made a mistake in describing the problem.

I had two jdbcTemplates in my dao.

So the way I resolved it is to use a @Qualifier(&quot;jdbcTemplate&quot;) when creating a mock jdbctemplate

huangapple
  • 本文由 发表于 2020年9月4日 00:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63727555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定