PowerMock没有抄袭正确的方法

问题描述 投票:1回答:2

我面临着一个奇怪的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调用,那么我会在第2行获得listNames而不是listPlaces。

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

junit4 powermock
2个回答
0
投票

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

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

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

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


0
投票

不同的观点。这里:

@InjectMocks
private TestMe testMeMock;

然后:

when(testMeMock.returnPlaces()).thenReturn(listPlaces); 

根本没有意义。

@InjectMocks注释用于创建被测试类的实例,该实例将通过@Mock注释“填充”您创建的其他模拟。但是你在测试实例下使用那个类就像是一个模拟(通过去when(testMeMock.foo()))。

你应该先退后一步,自己澄清你打算做什么。可能是部分嘲讽,因为你想测试你的init()方法,但你也打算控制你所测试的类上的其他方法。

最后,您可能还想退后一步,重新思考整体设计。要让公共方法返回列表,这些列表也用于执行init的公共方法,这听起来也是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.