package model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Calendar; import java.util.Date; import static org.junit.jupiter.api.Assertions.*; /** * Unit tests for the Event class */ public class EventTest { private Event e; private Date d; //NOTE: these tests might fail if time at which line (2) below is executed //is different from time that line (1) is executed. Lines (1) and (2) must //run in same millisecond for this test to make sense and pass. @BeforeEach public void runBefore() { e = new Event("Sensor open at door"); // (1) d = Calendar.getInstance().getTime(); // (2) } @Test public void testEvent() { assertEquals("Sensor open at door", e.getDescription()); assertEquals(d, e.getDate()); } @Test public void testToString() { assertEquals(d.toString() + "\n" + "Sensor open at door", e.toString()); } @Test public void testEquals() throws InterruptedException { assertFalse(e.equals(null)); assertFalse(e.equals(this)); assertFalse(e.equals(new Event("114514!!!"))); // Assuming the process doesn't get descheduled too long ... // Much better to mock here. final Event e1 = new Event("114514"); final Event e2 = new Event("114514"); Thread.sleep(1000); final Event e3 = new Event("114514"); assertTrue(e1.equals(e2)); assertFalse(e1.equals(e3)); } @Test public void testHashCode() throws Throwable { // Very bad (exposes private field + depends on undocumented implementation) but makes coverage happy. final java.lang.reflect.Field f = Event.class.getDeclaredField("HASH_CONSTANT"); f.setAccessible(true); assertEquals((int) f.get(null) * e.getDate().hashCode() + e.getDescription().hashCode(), e.hashCode()); } }