我想用测试的模拟对象创建一个JUnit测试:public class BinCountryCheckFilterImplTest { private RiskFilterService riskFilterService = null; @Before public void beforeEachTest() { List<RiskFilters> list = new ArrayList<RiskFilters>(); riskFilterService = Mockito.mock(RiskFilterService.class); // put here list of List<RiskFilters> and return it } @Test public void testBinCountryCheckFilterImpl() { List<RiskFilters> filter_list = riskFilterService.findRiskFiltersByTerminalIdAndType(11, "test"); // do something }}呼叫List<RiskFilters>时如何返回列表RiskFilterService?第二次尝试:public class BinCountryCheckFilterImplTest { private RiskFilterService riskFilterService = null; @Mock List<RiskFilters> mockList = new ArrayList<RiskFilters>(); @BeforeClass public void beforeEachTest() { //if we don't call below, we will get NullPointerException MockitoAnnotations.initMocks(this); mockList.add(new RiskFilters()); riskFilterService = Mockito.mock(RiskFilterService.class); } @Test public void testBinCountryCheckFilterImpl() { when(riskFilterService.findRiskFiltersByTerminalIdAndType(anyInt(), anyString())).thenReturn(mockList); List<RiskFilters> filter_list = riskFilterService.findRiskFiltersByTerminalIdAndType(11, "BinCountryCheckFilter"); }}但是我得到riskFilterService的NPE。看起来带有@test注释的方法在@BeforeClass之前被调用。 最佳答案 好吧,您提供的信息很少。 BUT让我通过您必须具有BinCountryCheckFilter类。请在您的测试课程中对其进行初始化,并添加注释@InjectMocks@InjectMockprivate BinCountryCheckFilter binCountryCheckFilter;从riskFilterService = Mockito.mock(RiskFilterService.class);中取出@BeforeClass并公开放置。但这只会嘲笑您的课程,不会进行任何测试。您可以测试的一件事就是没有打过电话。见下文verify(mockList, times(1)).yourMethodName();或在测试中或方法之前添加以下内容when(riskFilterService.yurMethodName).thenReturn(your Return value);这样,您将能够模拟所需的数据。让我知道是否需要其他清晰度。我不确定您的JUnit版本,但是可以删除现在从您的代码中获取 @Mock List<RiskFilters> mockList = new ArrayList<RiskFilters>();太。 08-06 19:32