diff --git a/src/main/java/org/kohsuke/github/GHCommitPointer.java b/src/main/java/org/kohsuke/github/GHCommitPointer.java index 41cb15114c..bebee145e9 100644 --- a/src/main/java/org/kohsuke/github/GHCommitPointer.java +++ b/src/main/java/org/kohsuke/github/GHCommitPointer.java @@ -52,10 +52,22 @@ public GHCommitPointer() { * @throws IOException * the io exception */ + + //original code + // public GHCommit getCommit() throws IOException { + // return getRepository().getCommit(getSha()); //when repo is null, so this will throw NPE + // } + + //fixed code public GHCommit getCommit() throws IOException { - return getRepository().getCommit(getSha()); + GHRepository repository = getRepository(); + if (repository == null) + throw new IOException("Cannot commit because repository is null."); + + return repository.getCommit(getSha()); } + /** * String that looks like "USERNAME:REF". * diff --git a/src/main/java/org/kohsuke/github/GHPullRequest.java b/src/main/java/org/kohsuke/github/GHPullRequest.java index 47636ce108..05a53a4e93 100644 --- a/src/main/java/org/kohsuke/github/GHPullRequest.java +++ b/src/main/java/org/kohsuke/github/GHPullRequest.java @@ -340,7 +340,7 @@ public URL getDiffUrl() { * @return the head */ public GHCommitPointer getHead() { - return head; + return head; //return head directly, no null check } /** diff --git a/src/test/java/org/kohsuke/github/GHCommitPointerTest.java b/src/test/java/org/kohsuke/github/GHCommitPointerTest.java new file mode 100644 index 0000000000..fd23c06e84 --- /dev/null +++ b/src/test/java/org/kohsuke/github/GHCommitPointerTest.java @@ -0,0 +1,31 @@ +package org.kohsuke.github; + +import org.junit.Assert; +import org.junit.Test; +import java.io.IOException; + +public class GHCommitPointerTest { + //week8 failing test: + //test the null value + // @Test + // public void nullRepoNpe() throws Exception { + + // GHCommitPointer pointer = new GHCommitPointer(); //new object value is null + // + // throws NPE because repository is null. + // pointer.getCommit(); + // } + + //week9 fixed test + //test the IOException, which is more controllable + @Test + public void nullRepoNpe() { + GHCommitPointer pointer = new GHCommitPointer(); + + //expect throw IOException, test fail otherwise + IOException ex = Assert.assertThrows(IOException.class, pointer::getCommit); //method reference + + //continue to test if error message also contains "repository is null", test fail otherwise + Assert.assertTrue(ex.getMessage().contains("repository is null")); + } +}