This is a basic reminder on how to declare packages
and import those packages when running Gradle tests.
Given the following example to test a Linked List
Java class, we have the following layout for the .java
and test files:
└── src ├── main │ └── java │ ├── LinkedList.java │ └── Node.java └── test └── java └── LinkedListTest.java
import main.java.Node; class LinkedList { Integer size; Node head; public LinkedList() { this.size = 0; this.head = null; } public LinkedList(Node head) { this.size = 1; this.head = head; } public Integer getSize() { return this.size; } public Node getFirst() { return this.head; } }
Notice here that the package itself is has the public
modifier and has the package main.java
itself declared.
package main.java; public class Node { private Integer data; private Node next; public Node(Integer data) { this.data = data; this.next = null; } public Node(Integer data, Node next) { this.data = data; this.next = next; } public void setNext(Node next) { this.next = next; } public Node getNext() { return this.next; } public void setData(Integer data) { this.data = data; } public Integer getData() { return this.data; } }
For this particular test, we also need to import the Node
package to ensure we can create nodes for the LinkedList.
import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; import main.java.Node; public class LinkedListTest { @Test public void testGetFirst() { Node n1 = new Node(2); LinkedList ll = new LinkedList(n1); assertEquals(ll.getFirst(), n1); } }