gpt4 book ai didi

java - @MockClass 不工作

转载 作者:行者123 更新时间:2023-11-30 07:02:19 25 4
gpt4 key购买 nike

我是 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;
}
}
};
}

删除过时的 block :

 public static class MockBookstoreService{...}

关于java - @MockClass 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29163453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com