我是jmockit的新手,并尝试执行以下在线示例。
@MockClass不起作用。我的BookStore的getBookTitle()方法调用了原始类的函数而不是mock类。
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
答案 0 :(得分:2)
使用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{...}