tiebin-zhang / powermock

Automatically exported from code.google.com/p/powermock
Apache License 2.0
0 stars 0 forks source link

mock(UUID.class) returns an actual UUID instance and not a mock. #354

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
UUID uuid = org.powermock.api.mockito.PowerMockito.mock(UUID.class) returns an 
actual UUID instance and not a mock.

I have this class:

public class SecurityService {
    public String generatePerishableToken() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

and the test class looks like:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ SecurityService.class })
public class SecurityServiceTest {

    private SecurityService service;
    private UUID uuid;

    @Before
    public void setUp() {
        service = new SecurityService();
        uuid = mock(UUID.class);
    }

    @Test
    public void testGeneratePerishableToken() {
        // given
        mockStatic(UUID.class);
        given(UUID.randomUUID()).willReturn(uuid);
        given(uuid.toString()).willReturn("my-perishable-token");

        // when
        String actual = service.generatePerishableToken();

        // then
        assertEquals("myperishabletoken", actual);
        // TODO verify
    }
}

Original issue reported on code.google.com by marceloverdijk on 2 Nov 2011 at 9:45

GoogleCodeExporter commented 9 years ago
It's not possible to solve. I've added some work-around to PowerMock trunk 
which makes you do like this:

    @Test
    public void mockingUUIDWorks() throws Exception {
        // given
        final UUID mock = mock(UUID.class);
        mockStatic(UUID.class);
        given(UUID.randomUUID()).willReturn(mock);

        // when
        String actual = new SystemClassUser().generatePerishableToken();

        // then
        assertEquals("00000000000000000000000000000000", actual);
    }

Original comment by johan.ha...@gmail.com on 3 Nov 2011 at 8:48