'how to mock UUID?

is it possible to mock UUID? or any problem in my Source Code?

Look at exmaple:

  1. MyTest Class

     @RunWith(PowerMockRunner.class)
     @PrepareForTest({UUID.class,ActualClass.class,MyTest.class})
     public class MyTest extends AbstractMuleContextTestCase{
     ActualClass obj=new ActualClass ();
     @Before
     public void setUp() throws Exception {
     final String id = "2f2ae98b-8fb2-4e2f-9913-65eaabdbcc29";
     ActualClass instance = PowerMockito.spy(new ActualClass ());
     PowerMockito.when(instance, 
     UUID.randomUUID().toString()).thenReturn(id);
       }
     }
    
  2. MyMain Class

    Class MyMain implements Callable {
    public Object onCall(MuleEventContext eventContext) throws Exception {
             //some function
    private String updatingUpdateQuery(){
    String uid=UUID.randomUUID().toString();
    //some function
      }
    }
    

how to mock String uid?

am getting following errors

     java.lang.IllegalStateException: Failed to transform class with name com.MyTest  Reason: 3
        at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:265)
        at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:179)
        at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:145)
        at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:40)
        at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:244)
        at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:61)
        at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:32)
        at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)


Solution 1:[1]

In my case, I was using JUnit 5 so I wasn't able to use PowerMock, and Mockito doesn't provide static methods mocking. I rewrote a bit my production code so that I didn't need to mock UUID static method.

I used Supplier interface

public class TestedClass {
    private final Supplier<UUID> uuidSupplier = UUID::randomUUID;

    public String getUuid() {
        return uuidSupplier.get().toString();
    }
}

Then I used reflection in order to test it

public class TestedClassTest {
    @Test
    public void testMethod() throws NoSuchFieldException, IllegalAccessException {
        Supplier<UUID> uuidSupplier = mock(Supplier.class);
        TestedClass testedClass = new TestedClass();
        Field uuidSupplierField = TestedClass.class.getDeclaredField("uuidSupplier");
        uuidSupplierField.setAccessible(true);
        uuidSupplierField.set(testedClass, uuidSupplier);

        String uuid = "5211e915-c3e2-4dcb-0776-c7b900f38ab7";
        when(uuidSupplier.get()).thenReturn(UUID.fromString(uuid));

        assertEquals(uuid, testedClass.getUuid());
    }
}

As recommended by the author of the question, here are my imports:

import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.util.UUID;
import java.util.function.Supplier;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

And here my dependencies:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.2.0</version>
    <scope>test</scope>
</dependency>

Hope it helps someone else.

Solution 2:[2]

Following the suggestion from @tifa, you can use ReflectionUtils.

ReflectionTestUtils.setField(testedClass, "uuidSupplier", uuidSupplier);

Solution 3:[3]

import static org.mockito.Mockito.mockStatic;
import org.junit.jupiter.api.BeforeAll;

class Tests{
    @BeforeAll
    static void setUp() {
        mockStatic(UUID.class);
        when(UUID.randomUUID()).thenReturn("static_uuid"));
    }
//tests
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Solksjaer
Solution 3 Muriithi Derrick