My question is about mocking a RevCommit
object from the JGit library.
When simply mocking an object of this type and defining it's behaviour, I get an error. For example:
RevCommit revCommitMock = mock(RevCommit.class);
Mockito.when(revCommitMock.getShortMessage()).thenReturn("ExampleMessage");
This will result in a NullPointerException
.
Probably, the way to do it correctly is calling method:
parse(RevWalk rw, byte[] raw)
on an instance of RevCommit
object, but how to do it properly? I get NullPointerException
parsing mocked object of type RevWalk
.
Thanks for any help in advance.
To avoid the NullPointerException
, you would need to fully simulate the behaviour of a real RevCommit
. To get its behaviour right in all aspects, you would end up re-building large parts of the actual RevCommit
implementation in JGit.
This is why I recommend to run tests against a real repository. For said reasons, it is usually not advisable to mock types that you don't own (see https://github.com/mockito/mockito/wiki/How-to-write-good-tests).
And with JGit it is very simple to create test-repositories:
public class JGitTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private Git git;
@Before
public void setUp() throws GitAPIException {
git = Git.init().setDirectory(tempFolder.getRoot()).call();
}
@After
public void tearDown() {
git.getRepository().close();
}
@Test
public void testFirst() {
// with 'git' you have access to a fully functional repository
}
}
See here for another example that initializes a repository and uses a TemporaryFolder
to clean up: https://gist.github.com/rherrmann/5341e735ce197f306949fc58e9aed141