001package edu.pdx.cs.joy.phonebill; 002 003import org.junit.jupiter.api.AfterEach; 004import org.junit.jupiter.api.BeforeEach; 005import org.junit.jupiter.api.Test; 006 007import java.sql.*; 008 009import static org.hamcrest.MatcherAssert.assertThat; 010import static org.hamcrest.Matchers.*; 011 012/** 013 * A simple example unit test that demonstrates persisting a PhoneBill 014 * to an H2 in-memory database using JDBC. 015 * 016 * This is a starting point for students to understand how to use 017 * Data Access Objects (DAOs) to persist domain objects to a database. 018 */ 019public class PhoneBillDAOTest { 020 021 private Connection connection; 022 private PhoneBillDAO dao; 023 024 @BeforeEach 025 public void setUp() throws SQLException { 026 // Create an in-memory H2 database 027 connection = DriverManager.getConnection("jdbc:h2:mem:phonebill_test"); 028 029 // Create the phone_bills table 030 PhoneBillDAO.createTable(connection); 031 032 // Create the DAO 033 dao = new PhoneBillDAO(connection); 034 } 035 036 @AfterEach 037 public void tearDown() throws SQLException { 038 if (connection != null && !connection.isClosed()) { 039 connection.close(); 040 } 041 } 042 043 @Test 044 public void canPersistAndFetchPhoneBillByCustomerName() throws SQLException { 045 String customerName = "Jane Doe"; 046 PhoneBill bill = new PhoneBill(customerName); 047 048 // Persist the phone bill using the DAO 049 dao.save(bill); 050 051 // Fetch the phone bill by customer name 052 PhoneBill fetchedBill = dao.findByCustomer(customerName); 053 054 // Validate that the fetched bill matches the original 055 assertThat(fetchedBill, is(notNullValue())); 056 assertThat(fetchedBill.getCustomer(), is(equalTo(customerName))); 057 } 058 059 @Test 060 public void returnsNullWhenPhoneBillNotFound() throws SQLException { 061 PhoneBill fetchedBill = dao.findByCustomer("Non-existent Customer"); 062 assertThat(fetchedBill, is(nullValue())); 063 } 064} 065