Search code examples
javaunit-testingjunitmockito

Mockito - Mocking a method with parameters


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,


Solution

  • 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/

    UPDATED at 2023-09-18 Unfortunately the above link is broken. But I found most of the material referenced here:

    Interested readers will skim https://www.google.com/search?q=site%3Atesting.googleblog.com%20misko%20hevery