1

I am writing unit tests for a method that takes in argument id which is something like below :

 public void searchid(String id) {
    Document doc = Repository.findDocument(id); //returns a document
    if (doc == null) {
      System.out.println("id missing");
    } else {
      String stringRecord = doc.asJsonString(); //converting doc to string

Here Repository.findDocument(id) is returning a document. In my unit test, I am getting the JSON file from src/test/resources. So, how do I mock Repository.findDocument(id), so as to fetch the file from my resource instead ?

Thanks,

AYa
  • 421
  • 3
  • 9
  • 21

2 Answers2

2

You can try to mock the Repository.findDocument(id) call in your unit test method.

Mockito.when(Repository.findDocument(Mockito.isA(String.class))).thenReturn(Mockito.mock(Document.class));

This will return Mocked Document object whenever the Repository.findDocument(id) call is made.

Venkat
  • 56
  • 4
  • So, I should parse the JSON file and store the ID and pass it in the above function ryt ? – AYa Sep 13 '17 at 11:41
  • Sorry didn't notice that you need Document object, I have edited my answer. If you wish to mock Document object with custom data you could do it. – Venkat Sep 13 '17 at 11:49
  • And where should I call my method `searchid(id)` ? – AYa Sep 13 '17 at 11:50
  • Both the mocking code and `searchid(id)` should be in your unit test method – Venkat Sep 13 '17 at 11:55
  • Hey, how can I mock Document object with custom data ? Sorry to ask but I am a newbie to this. – AYa Sep 13 '17 at 12:15
1

The key to testability is that you have a field repository that gets constructor-injected into your class. This way you can easily substitute the real repository by a fake instance (e.g a mockito mock).

The best source for learning how to write testable code, that I know, is http://misko.hevery.com/code-reviewers-guide/

Frank Neblung
  • 3,047
  • 17
  • 34