PowerMockito .when().thenReturn() with randomUUID not returning expected value [duplicate]

半城伤御伤魂 提交于 2019-12-05 16:22:45

Common mistake with mocking system classes it's that they are added to @PrepareForTest, but unfortunately it's impossible to mock final Java System classes directly. But PowerMock provides workaround. PowerMock replaces calls to system classes by call to PowerMock class. A class that use final system class should be added to @PrepareForTest

I've added example how to mock UUID.

public class DocumentService {

  public JsonDocument saveDocument(JsonDocument document){
    UUID uuid = UUID.randomUUID();
    document.setId(uuid.toString());
    return document;
  }
}

Test

@RunWith(PowerMockRunner.class)
@PrepareForTest(DocumentService.class)
public class DocumentServiceTest {
@Test
public void should_set_id() throws Exception {
    final String id = "493410b3-dd0b-4b78-97bf-289f50f6e74f";
    UUID uuid = UUID.fromString(id);

    mockStatic(UUID.class);
    when(UUID.randomUUID()).thenReturn(uuid);

    DocumentService documentService = new DocumentService();

    JsonDocument document = new JsonDocument();
    documentService.saveDocument(document);

    assertThat(document.getId())
        .as("Id is set")
        .isEqualTo(id);
  }
}

You may find more in documentation.

I've reused and modified @hammerfest s example a bit which work on my machine.

The first case simply mocks the static invocation of the UUID class and asserts that the returned UUID of the SUT equals the mocked UUID:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.UUID;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@PrepareForTest({ UUID.class })
@RunWith(PowerMockRunner.class)
public class StaticMockTest {

  @Test
  public void test() {
    MyClass sut = new MyClass();

    UUID uuidLocal = UUID.randomUUID();
    mockStatic(UUID.class);
    when(UUID.randomUUID()).thenReturn(uuidLocal);

    assertThat(sut.getUUID(), is(equalTo(uuidLocal)));
  }

  private class MyClass {

    public UUID getUUID() {
      return UUID.randomUUID();
    }
  }
}

The second case invokes a method of a Spring managed bean which returns the mocked UUID:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DefaultTestContextBootstrapper;

import java.util.UUID;

import javax.annotation.Resource;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@PrepareForTest({ UUID.class })
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@BootstrapWith(DefaultTestContextBootstrapper.class)
@ContextConfiguration(classes = {StaticMockTest2.ContextConfig.class},
    loader= AnnotationConfigContextLoader.class)
@PowerMockIgnore({"javax.management.*"})
public class StaticMockTest2 {

  @Resource
  private MyClass sut;

  @Test
  public void test() {

    UUID uuidLocal = UUID.randomUUID();
    mockStatic(UUID.class);
    when(UUID.randomUUID()).thenReturn(uuidLocal);

    assertThat(sut.getUUID(), is(equalTo(uuidLocal)));
  }

  private static class MyClass {

    public UUID getUUID() {
      return UUID.randomUUID();
    }
  }

  @Configuration
  public static class ContextConfig {

    @Bean
    public MyClass myClass() {
      return new MyClass();
    }
  }
}

Both tests work on my machine though I'd suggest to refactor the UUID generation into a utility class which you instantiate and inject via Spring. Then you can simply replace the PowerMock stuff with ordinary Mockito mocking and avoid dealing with such problems:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import java.util.UUID;

import javax.annotation.Resource;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MockTest3.ContextConfig.class},
    loader= AnnotationConfigContextLoader.class)
public class MockTest3 {

  @Resource
  private Util mockUtil;
  @Resource
  private MyClass sut;

  @Test
  public void test() {

    UUID uuidLocal = UUID.randomUUID();
    when(mockUtil.generateUUID()).thenReturn(uuidLocal);

    assertThat(sut.getUUID(), is(equalTo(uuidLocal)));
  }

  private static class MyClass {

    private Util util;

    public MyClass(Util util) {
      this.util = util;
    }

    public UUID getUUID() {
      return util.generateUUID();
    }
  }

  private static class Util {

    public UUID generateUUID() {
      return UUID.randomUUID();
    }
  }

  @Configuration
  public static class ContextConfig {

    @Bean
    public Util mockUtil() {
      return mock(Util.class);
    }

    @Bean
    public MyClass myClass() {
      return new MyClass(mockUtil());
    }
  }
}

If you don't want to rely on Spring for testing (to speed up things even further) you can inject the dependencies yourself either via constructor injection or via Whitebox.setInternalState(sut, "fieldName", mockObject); or Springs ReflectionUtils.setField(sut, "fieldName", mockObject);.

import org.junit.Test;
import org.mockito.internal.util.reflection.Whitebox;

import java.util.UUID;

import javax.annotation.Resource;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

public class MockTest4 {

  @Test
  public void test() {

    Util mockUtil = mock(Util.class);
    MyClass sut = new MyClass(mockUtil);

//    MyClass sut = new MyClass();
//    Whitebox.setInternalState(sut, "util", mockUtil);

    UUID uuidLocal = UUID.randomUUID();
    when(mockUtil.generateUUID()).thenReturn(uuidLocal);

    assertThat(sut.getUUID(), is(equalTo(uuidLocal)));
  }

  private class MyClass {

    @Resource
    private Util util;

    public MyClass() {}
    public MyClass(Util util) {
      this.util = util;
    }

    public UUID getUUID() {
      return util.generateUUID();
    }
  }

  private class Util {

    public UUID generateUUID() {
      return UUID.randomUUID();
    }
  }
}

The last test contains both options, constructor or field injection, you can play with.


Due to @hammerfest s comment I'm adding a further example here that showcases what to do if MyClass is externally defined. Note this example was basically taken from Github before I read the answer of @ArthurZagretdinov, who is probably the author of this test in first place (as pointed out by @hammerfest in the comments). First the standalone MyClass implementation:

import java.util.UUID;

public class MyClass {

  public UUID getUUID() {
    return UUID.randomUUID();
  }
}

Next, the test that uses the external MyClass definition:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.UUID;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@PrepareForTest({ MyClass.class })
@RunWith(PowerMockRunner.class)
public class StaticMockTest3 {

  @Test
  public void test() {
    MyClass sut = new MyClass();

    final String id = "493410b3-dd0b-4b78-97bf-289f50f6e74f";
    UUID uuid = UUID.fromString(id);

    // UUID uuidLocal = UUID.randomUUID();
    mockStatic(UUID.class);
    when(UUID.randomUUID()).thenReturn(uuidLocal);
    // when(UUID.randomUUID()).thenReturn(uuidLocal);

    assertThat(sut.getUUID().toString(), is(equalTo(uuid.toString())));
  }
}

If you comment out both comment-lines in the above cenario, you will figure out that the test will fail due to unequal UUIDs. This means that the preparation for MyClass does also respect using the declared UUID mock and thus can be used for mocking static classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!