两个类都以静态方法结尾:UUID(java),BUKKIT(spigot-api)。
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* TempTest.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({Bukkit.class, UUID.class})
public class TempTest {
@Mock
private Player player;
private UUID uuid = UUID.fromString("6ba38d11-e901-4d81-950b-d9743e4a98fa");
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(Bukkit.class, UUID.class);
}
@Test
public void testPlayer() {
when(Bukkit.getPlayer("test")).thenReturn(player);
Player actualPlayer = Bukkit.getPlayer("test");
assertEquals(player, actualPlayer);
}
@Test
public void testUuid() {
when(UUID.randomUUID()).thenReturn(uuid);
UUID actualUuid = UUID.randomUUID();
assertEquals(uuid, actualUuid);
}
}
第一个测试工作正常,第二个测试在代码的第一行失败:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.util.UUID
Mockito cannot mock/spy because :
- final class
at com.gmail.nodondarkeye.plugintutorial.TempTest.testUuid(TempTest.java:47)
为什么一个测试失败而另一个没有失败。只是似乎找不到明显的区别,而且我的测试代码也没有看到任何错误。欢迎所有见解。