看起来我好像遇到了我自己无法解决的麻烦。这里的故事:我有一个任务,我应该学习mockito框架和测试耦合方法。不允许在内存数据库中使用。
在OrderDaoImpl类中return new Order(resultSet.getString(name));
我得到DomainArgumentValidationException: Can not be null
。
查看Order的构造函数:
public class Order {
private String name;
private Set<Good> goods = new HashSet<>();
public Order(String name) {
Util.assertValidName(name);
this.name = name;
}
setters, getters...
如果我理解正确new Order()
对象必须有正确的名称,否则他无法创建。名称不能为空。这就是我头疼的原因。
如何让resultSet在new Order(resultSet.getString(name)
传递String?
如果我的结论错了,请帮助我了解这里发生了什么,以及如何做到正确。
这是我的测试方法:
class OrderDaoImpl {
private DaoFactory daoFactory = new DaoFactory();
Order retrieveByName(String name) throws Exception {
String sql = "select * from orders where name = ?;";
try (Connection connection = daoFactory.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
preparedStatement.execute();
ResultSet resultSet = preparedStatement.getResultSet();
resultSet.next();
return new Order(resultSet.getString(name));
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
这是我的junit测试:
@RunWith(MockitoJUnitRunner.class)
public class OrderDaoImplTest {
@InjectMocks
OrderDaoImpl orderDao = new OrderDaoImpl();
@Mock
DaoFactory mockDaoFactory;
@Mock
Connection mockConnection;
@Mock
PreparedStatement mockPreparedStatement;
@Mock
ResultSet mockResultSet;
@Test
public void testRetrieveByName() throws Exception {
// Set Up
String sql = "select * from orders where name = ?;";
String orderName = "Test";
Answer<String> answer = new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
String string = invocation.getArgumentAt(0, String.class);
return string;
}
};
// Mock expectations
when(mockDaoFactory.getConnection()).thenReturn(mockConnection);
when(mockConnection.prepareStatement(sql)).thenReturn(mockPreparedStatement);
doNothing().when(mockPreparedStatement).setString(1, cathedraName);
when(mockPreparedStatement.execute()).thenReturn(true);
when(mockPreparedStatement.getResultSet()).thenReturn(mockResultSet);
when(mockResultSet.next()).thenReturn(true).thenReturn(false);
when(mockResultSet.getString(orderName)).thenAnswer(answer);
// Execute the method being tested
orderDao.retrieveByName(orderName);
// Validation
assertThat(orderDao.retrieveByName(orderName), is(new Order(orderName)));
verify(mockDaoFactory, times(1)).getConnection();
verify(mockConnection, times(1)).prepareStatement(sql);
verify(mockPreparedStatement, times(1)).setString(1, orderName);
verify(mockPreparedStatement, times(1)).execute();
verify(mockPreparedStatement, times(1)).getResultSet();
verify(mockResultSet, times(1)).next();
verify(mockResultSet, times(1)).getString(orderName);
}
}