gpt4 book ai didi

java - 为什么模拟的类不会进入未模拟的函数?

转载 作者:行者123 更新时间:2023-12-02 10:58:27 26 4
gpt4 key购买 nike

我有一个类:

@Component
public class GCInitializer
{
@Autowired
GCGoodRepository gcGoodRepository;

@PostConstruct
public void onStartup() throws Exception
{
// load/update base data
initGCBaseData();
}

private void initGCBaseData() throws Exception
{
ArrayList<GCGood> dbGoods;
ArrayList<GCGood> fileGoods;
ArrayList<GCGood> baseGoods;

dbGoods = getGCGoodsFromDB();
fileGoods = getGoodsFromFile();
baseGoods = getGoodsFromInitializer();

// do my merge magic
[…]
}

private ArrayList<GCGood> getGoodsFromInitializer() {
ArrayList<GCGood> baseGoods = new ArrayList<>();
[…]
}
[…]
}

此类在启动时搜索三个不同的数据源以获取不同的商品并将它们组合起来而不重复。

现在我想用 Mockito 编写单元测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class GCInitializerTest {

@Autowired
GCGoodRepository gcGoodRepository;

@Test
public void onStartupFirstTime() throws InvocationTargetException, IllegalAccessException
{
// normal Start: after Start there are only 7 goods in it!!! (Db far away Off, File empty => only Standards!!!)
GCInitializer gcInitializer = Mockito.mock(GCInitializer.class);
Mockito.when(gcInitializer.getGoodsFromFile()).thenReturn(null);
Mockito.when(gcInitializer.getGCGoodsFromDB()).thenReturn(null);
ReflectionTestUtils.setField(gcInitializer, "gcGoodRepository", gcGoodRepository);
gcGoodRepository.deleteAll();

// private invokation of GCInitializer::initGCBaseData()
Method method = GCInitializer.class.getDeclaredMethod("initGCBaseData");
method.setAccessible(true);
method.invoke(gcInitializer);

assertEquals(Lists.newArrayList(gcGodRepository.findAll()).size(), 7);
}
[...]
}

使用调试器运行函数 GCInitializer::getGoodsFromInitializer() 永远不会输入并返回 null,而不是具有 7 个 GCGood 的数组。

为什么会这样呢?我怎样才能让这个函数返回正确的ArrayList?

最佳答案

我确实同意备忘录,但如果你想这样做,你仍然可以使用真正的部分模拟 https://static.javadoc.io/org.mockito/mockito-core/2.20.0/org/mockito/Mockito.html#16例如:

when(mock.someMethod()).thenCallRealMethod();

关于java - 为什么模拟的类不会进入未模拟的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51535559/

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