mock dao在保存对象时返回false



我是测试驱动开发的新手。我试图测试一个对象是否已成功保存到我的数据库中。我的代码到目前为止:

@ExtendWith(MockitoExtension.class)
public class ParkingDataBaseIT {
@Mock
private TicketDAO mockTicketDAO;

@Mock
public static DataBaseTestConfig mockDataBaseTestConfig = new DataBaseTestConfig();

@Mock
private static Connection mockConnection;
@BeforeEach
public void setup() throws SQLException, ClassNotFoundException {
// Connection attempt.
when(mockDataBaseTestConfig.getConnection()).thenReturn(mockConnection);
}
@AfterAll
public static void tearDown() {
// ...
}
@DisplayName("Tests if saving a ticket is successful.")
@Test
public void testParkingACarAlpha() throws SQLException, ClassNotFoundException {
// Given.
Date inTime = new Date();
Ticket ticket = new Ticket();

ticket.setVehicleRegNumber("ABCDEF");
ticket.setPrice(0);
ticket.setInTime(inTime);
ticket.setOutTime(null);

// When.
// MockDao always returning false when saving.
final boolean saved = mockTicketDAO.saveTicket(ticket, mockDataBaseTestConfig.getConnection());

// Then.
assertEquals(true, saved);
assertThat(saved).isEqualTo(true);
}
}

这是连接MySQL的方法:

public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/testing", "root", "");
}

最后,我是这样保存我的票的:

public boolean saveTicket(Ticket ticket, Connection con) {
try {
PreparedStatement ps = con.prepareStatement("insert into ticket(vehicleRegNumber, price, inTime, outTime) values(?, ?, ?, ?, ?)");

ps.setInt(1, ticket.getParkingSpot().getId());
ps.setString(2, ticket.getVehicleRegNumber());
ps.setDouble(3, ticket.getPrice());
ps.setTimestamp(4, new Timestamp(ticket.getInTime().getTime()));
ps.setTimestamp(5, (ticket.getOutTime() == null) ? null: (new Timestamp(ticket.getOutTime().getTime())));

return ps.execute();
} catch (Exception e) {
logger.error("Cannot fetch available slot.", e);
} finally {
dataBaseConfig.closeConnection(con);
}

return false;
}

使用MySQL的请求工作,但在保存对象时,我从ps.execute()得到一个false;虽然不是真的,但我肯定做错了什么。

我注意到pssaveTicket(Ticket ticket, Connection con)中是空的(不能调用"java.sql.PreparedStatement。setInt (int, int)";因为"ps"是null),但con有mockConnection时,我sysout的值。

由于mockDataBaseTestConfig.getConnection()总是返回null,显然它不能工作。

在审查之后,我只通过模拟dao来结束它的工作(注意,测试已被重命名为testSavingTicket_shouldReturnTrue)。

private Ticket t;
@Test
public void testSavingTicket_shouldReturnTrue() throws SQLException, ClassNotFoundException {
// Given.
TicketDAO mockTicketDao = mock(TicketDAO.class);

t = new Ticket();

t.setVehicleRegNumber("ABCDEF");
t.setPrice(0);
t.setInTime(new Date());
t.setOutTime(null);

when(mockTicketDao.saveTicket(t)).thenReturn(true);

// When.
final boolean saved = mockTicketDao.saveTicket(t);

// Then.
assertEquals(true, saved);
assertThat(saved).isEqualTo(true);
}

最新更新