2

有谁知道在不调用 replayAll() 的情况下模拟静态类的方法?我见过很多人们嘲笑 Math.random() 并使用 replayAll() 的例子。对我来说,似乎 replayAll() 是处理事情的更懒惰的方式,但我还没有找到一种方法来使用 replay(Object mocks) 来模拟静态方法。

例如,考虑我在 PowerMockTutorial上找到的以下示例:

public class Dice {
   public int sumOfNumDieRolls (int num) { 
      int sum = 0;
      for (int i=0;   i<num;   ++i) {
         int roll = (int) (6. * Math.random()) + 1;
         sum += roll;
      }
      return sum;
   }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest( {Dice.class} )
public class DiceTest {
   @Test
   public void shouldAddUpDieRollsCorrectly() {
      PowerMock.mockStaticPartial(Math.class, "random");
      EasyMock.expect (Math.random()).andReturn(0.3334).anyTimes();
      Dice die = new Dice();
      PowerMock.replayAll();
      assertEquals (12, die.sumOfNumDieRolls(4));
      assertEquals (30, die.sumOfNumDieRolls(10));
      PowerMock.verifyAll();
   }
}

我正在使用 PowerMock 1.4.10 版。

4

1 回答 1

1

您可以通过使用 PowerMock.replay([object_name]) 来做到这一点,这样您就不必全部重播。对于此示例,它将如下所示:

public class Dice {
   public int sumOfNumDieRolls (int num) { 
      int sum = 0;
      for (int i=0;   i<num;   ++i) {
         int roll = (int) (6. * Math.random()) + 1;
         sum += roll;
      }
      return sum;
   }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest( {Dice.class} )
public class DiceTest {
   @Test
   public void shouldAddUpDieRollsCorrectly() {
      PowerMock.mockStaticPartial(Math.class, "random");
      EasyMock.expect (Math.random()).andReturn(0.3334).anyTimes();
      Dice die = new Dice();
      PowerMock.replay(Math.class);
      assertEquals (12, die.sumOfNumDieRolls(4));
      assertEquals (30, die.sumOfNumDieRolls(10));
      PowerMock.verify(Math.class);
   }
}
于 2013-07-12T16:24:29.620 回答