首页 > 解决方案 > PowerMock 没有存根正确的方法

问题描述

我正面临一个奇怪的 PowerMock 问题。让我更详细地解释一下。

我的代码:

@Service 
public class TestMe {

  @Autowired
  private ClassA  a;

  @Autowired
  private ClassB  b;

  @Autowired
  private ClassStatic  staticClass;

  public void init(){
       List<String> nameList = returnNames(); // Line#1
       // Work with names 

       List<String> placeList = returnPlaces(); // Line#2
       // Work with places 
  }


  public List<String> returnNames(){
      // Code to return list of names
  }

  public List<String> returnPlaces(){
      // Code to return list of places
  }

}

我的测试班

 @RunWith(PowerMockRunner.class)
 @PrepareForTest({ClassStatic.class})
 public class TestMeTest {

 @Mock
 private ClassA  aMock;

 @Mock
 private ClassB  bMock;

 @InjectMocks
 private TestMe testMeMock;

 @Test
 public void testInit(){
     List<String> listNames = ... // some list of names 
     List<String> listPlaces = ... // some list of places

     when(testMeMock.returnNames()).thenReturn(listNames);

    // listPlaces gets returned in Line#1 shown in the main code.
     when(testMeMock.returnPlaces()).thenReturn(listPlaces); 
     testMeMock.init();
 }

}

因此,正如您在第 1 行中看到的那样,我得到的是 listPlaces 而不是 listNames。如果我重新安排 when 调用,那么我会在 Line#2 处得到 listNames 而不是 listPlaces。

为什么 PowerMock 与方法混淆?或者在使用 PowerMock 时我还缺少其他一些东西。

标签: junit4powermock

解决方案


我可以通过使用 thenReturn 两次来解决这个问题,如下所示

when(testMeMock.returnNames()).thenReturn(listNames).thenReturn(listPlaces); 

// Removed the returnPlaces() call 
// when(testMeMock.returnPlaces()).thenReturn(listPlaces); 
 testMeMock.init();

但是为什么 PowerMock 不能区分两个不同的方法调用 returnNames() 和 returnPlaces()?


推荐阅读