我是jmockit的新手,正在尝试执行以下在线示例。
@MockClass无法正常工作。我的BookStore的getBookTitle()方法正在调用原始类的函数,而不是模拟类。
BookStore类:
public class BookStore {
public String getBookTitle(String isbn){
return BookStoreService.getBookTitle(isbn);
}
}
BookStoreService类:
public class BookStoreService {
public static String getBookTitle(String isbn){
return "Random";
}
}
测试类别:
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:我正在使用TestNG
最佳答案
使用latest stable version of jmockit可以这样:
@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;
}
}
};
}
删除过时的块:
public static class MockBookstoreService{...}