Mockito无法模拟ThreadLocalRandom

时间:2018-09-01 07:34:49

标签: powermockito

我正在尝试在JUnit测试中模拟 ThreadLocalRandom

@RunWith(PowerMockRunner.class)
public class SomeTest {

    List<Game> games;

    @Before
     public void setUp() throws Exception {
        mockStatic(ThreadLocalRandom.class);
        when(ThreadLocalRandom.current()).thenReturn(any(ThreadLocalRandom.class));
        when(ThreadLocalRandom.current().nextInt(any(Integer.class))).thenReturn(1);
       games = Arrays.asList(new Game1(), new Game2());
   }

   @PrepareForTest({ ThreadLocalRandom.class })
   @Test
   public void someTestName() {
       assertTrue(new Game(games).winner().equals(new Game1()));
   }
}

在运行测试时,出现类似错误

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded:

任何输入如何解决此问题?

public class Toss {

    private final List<Game> games;

    public Toss(List<Game> games) {
        this.games = games;
    }

    public Game winner() {
        return games.get(ThreadLocalRandom.current().nextInt(games.size()));
    }
}

任何输入我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

when(ThreadLocalRandom.current()).thenReturn(any(ThreadLocalRandom.class));

没有任何意义。您不能告诉Mockito(或PowerMock)只返回它喜欢的任何旧ThreadLocalRandom。您需要告诉它要返回哪个对象。因此,实例化ThreadLocalRandom并使用在thenReturn之后创建的对象。