【问题标题】:Powermock: returning mocked objects while using a spied class failedPowermock:在使用间谍类时返回模拟对象失败
【发布时间】:2016-08-12 16:45:19
【问题描述】:

我正在测试一个具有私有方法“getEntityManager”的类。此方法返回要在公共方法“getAllProducts”中使用的实体管理器实例。所以我使用 PowerMockRunner; 我的依赖是:

junit-4.1.2
mockito-all-1.10.19
powermock-module-junit4- 1.6.5
powermock-api-mockito-1.6.5
javassist-3.12.1.GA

Hier 是我的(@GhostCat 增强版)代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ProduktDB.class)
public class ProduktDBTest {

  static final String PRODUCTID= "id";
  List<Product> productList;
  EntityManager emmock;
  Query q;

  @Before
  public void setUp() throws Exception {
    basicProductList= new ArrayList<>();
    BasicProductDao basicProductDao= new BasicProductDao();
    basicProductDao.setId(PRODUCTID);
    basicProductList.add(basicProductDao);

    emmock= mock(EntityManager.class);
    q= mock(Query.class);
  }

  @Test
  public void getAllProducts() throws Exception {
    when(emmock.createQuery(anyString())).thenReturn(q);
    when(q.getResultList()).thenReturn(productList);      
    ProduktDB spied= spy(new ProduktDB());

  /* ***********this is the line with the error:****** */
   PowerMockito.doReturn(emmock).when(spied, "getEntityManager"); 

    assertEquals(spied.getAllProducts().get(0).getId(),PRODUCTID );
  }
}

但是,当我想在调用私有方法时添加返回值时出现以下错误:

java.lang.NullPointerException
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:68)

现在我将临界线更改为以下内容:

  PowerMockito.when(spied, "getEntityManager").thenReturn(emmock);

不,我收到另一个错误,但它是无害的(请参阅下面的解决方案)。 :)

【问题讨论】:

  • 旁注:不要在变量名中使用“_”。除了像 PRODUCT_ID 这样的常量。并且方法名应该是驼峰式。与其直接调用 prepareList(),不如考虑使用 @Before。最后:如果您在这里没有得到好的答案,请尝试使用 google groups for powermock。最后:你有一个行号异常。如果您告诉我们代码中的哪一行给出了该异常,您不认为这会有所帮助吗?
  • 请添加完整的堆栈跟踪,而不仅仅是最后一行异常。

标签: powermock private-methods spy


【解决方案1】:

新的错误是:

 org.mockito.exceptions.misusing.MissingMethodInvocationException: 
 ...
 ...
 at org.powermock.api.extension.reporter.MockingFrameworkReporterFactoryImpl$PowerMockitoReporter.missingMethodInvocation(MockingFrameworkReporterFactoryImpl.java:66)
at de.ams.dpag.produktdb.ProduktDBAdapterTest.getAllProducts(ProduktDBAdapterTest.java:72)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at ...
....

原因是“getEntityManager”调用了基类的静态方法。我也必须 mocStatic(BaseclassWitStaticMethod),然后添加预期回报 对它的价值是这样的:

@PrepareForTest({ProduktDB.class, BaseClasswithStaticMethod.class})
...
    ProduktDB spied= spy(new ProduktDB());
    mockStatic(BaseClasswithStaticMethod.class);
    when(BaseClasswithStaticMethod.getEntityManager()).thenReturn(emmock);
  ...

测试通过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多