Search code examples
javatestingmockingtestngjmockit

@MockClass is not working


I am new to jmockit and trying to execute the following online example.

The @MockClass is not working. My BookStore's getBookTitle() method is calling the function of orginal class instead of the mock class.

BookStore class:

public class BookStore {

  public String getBookTitle(String isbn){
    return BookStoreService.getBookTitle(isbn);
  }
} 

BookStoreService class:

public class BookStoreService {

  public static String getBookTitle(String isbn){
    return "Random";
  }
}

Test class:

public class BookStoreTest {

  private static Map<String, String> bookMap = new HashMap<String, String>(2);

  @BeforeClass
  public static void setup() {
    System.out.println("in setup()");
    bookMap.put("0553293354", "Foundation");
    bookMap.put("0836220625", "The Far Side Gallery");
  }

  @MockClass(realClass = BookStoreService.class)
  public static class MockBookstoreService {
    @Mock
    public static String getBookTitle(String isbn) {
        System.out.println("in getBookTitle()");
        if (bookMap.containsKey(isbn)) {
            return bookMap.get(isbn);
        } else {
            return null;
        }
    }
  }

  @Test
  public void testGetBookTitle() throws Exception {
    System.out.println("in testGetBookTitle()");
    final String isbn = "0553293354";
    final String expectedTitle = "Foundation";
    BookStore store = new BookStore();
    String title = store.getBookTitle(isbn);
    System.out.println(title); // This prints "Random" instead of "Foundation"
    Assert.assertEquals(title, expectedTitle);
  }


}

PS: I am using TestNG


Solution

  • Using the latest stable version of jmockit you could do it like this:

    @BeforeClass
    public static void setup() {
        System.out.println("in setup()");
        bookMap.put("0553293354", "Foundation");
        bookMap.put("0836220625", "The Far Side Gallery");
    
        new MockUp<BookStoreService>() {            
            @Mock
            public String getBookTitle(String isbn) {
                System.out.println("in getBookTitle()");
                if (bookMap.containsKey(isbn)) {
                    return bookMap.get(isbn);
                } else {
                    return null;
                }
            }
        };
    }
    

    Remove the obsolete block:

     public static class MockBookstoreService{...}