不会为同一个类两次调用ExpectNew

问题描述

我正在使用EasyMock编写junit测试。因此对于一个对象:-

DataProvider dataProvider = new DataProvider(Data data,Provider provider);

所以我不得不模拟两次行为,就像这样:-

@Mock
DataProvider dataProvider1,dataProvider2;
   1. PowerMock.expectNew(DataProvider.class,dataRequest,provider1).thenReturn(mockDataProvider1);
   2. PowerMock.replay(DataProvider.class);
   3. PowerMock.expectNew(DataProvider.class,provider2).thneReturn(mockDataProvider2);
   4. PowerMock.replay(DataProvider.class);

但是当我尝试执行this时。这在第2行抛出错误。 当我删除第3行和第4行时,它成功了,没有任何问题。

我需要在自己的行为中使用两次。有人可以帮忙吗?

解决方法

replay()方法不应在同一测试方法中被同一类调用两次。

所以:-

   1. PowerMock.expectNew(DataProvider.class,dataRequest,provider1).thenReturn(mockDataProvider1);
   3. PowerMock.expectNew(DataProvider.class,provider2).thneReturn(mockDataProvider2);
   4. PowerMock.replay(DataProvider.class);

这东西有用。

对mockStatic()函数也有相同的建议。

一个人还应该记住,在一个测试方法中,对一个类只使用一次mockStatic()函数。 所以:-

PowerMock.mockStatic(DataProvider.class);

在测试方法中只能使用一次。