gpt4 book ai didi

java - PowerMockito .when().thenReturn() with randomUUID 不返回期望值

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:48 31 4
gpt4 key购买 nike

<分区>

我正在尝试测试连接到包含 JCR 节点的 SQL Server 数据库的 Web 服务方法,因为我们正在使用 JackRabbit。

方法如下:

public String addDocumentByJson(String fileName, byte[] fileContent, int status, String userName, String jsonProperties) {
UUID id = UUID.randomUUID();
// It does a bunch of operations here
return jsonResult;
}

其中jsonResult是一个类似于这个的对象:

{
"id" : "<A random UUID>"
"version" : 1
}

现在,当我尝试按照 this answer 中的步骤测试它时和 this post 中的代码我得到了以下代码(正如我所说,它基于过去的链接):

@PrepareForTest({ UUID.class })
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/TestSpringConfig.xml")
public class TestJackRabbitService {

@Autowired
@Qualifier("jackRabbitService")
IJackRabbitService jackRabbitService;

private byte[] fileContent;
private int versionFile;

public TestJackRabbitService() {
classLoader = getClass().getClassLoader();
}
@BeforeClass
public static void init() {
LOG.trace("Run @BeforeClass");
try {
fileContent = IOUtils.toByteArray(new FileInputStream(new File(Thread.currentThread().getContextClassLoader().getResource("fileTest.txt"))));
} catch (Exception e) {
LOG.error(ExceptionUtils.getStackTrace(e));
}
}

@Before
public void before() {
LOG.trace("Run @Before");
try {
versionFile = jackRabbitService.getLastVersionOf(nameApp, nameFile); //This method returns an int,
} catch (Exception e) {
LOG.error(ExceptionUtils.getStackTrace(e));
}
}

@Test
public void testAddDocumentsByJson() {
//Some tests which run correctly

final UUID uuid = UUID.randomUUID();
mockStatic(UUID.class);
LOG.debug(uuid);
//doReturn(uuid).when(UUID.randomUUID());
when(UUID.randomUUID()).thenReturn(uuid);
idFile = uuid;

assertEquals(jackRabbitService.addDocumentByJson(nameFile, bytes, nameApp, 5, jsonproperties), "{\"id\":\"" + uuid + "\",\"version\":1}");
}
}

然而,当我测试这个方法时,它给了我以下结果:

Results :

Failed tests:
testAddDocumentsByJson(com.optimissa.test.junit.TestJackRabbitService): expected:<{"id":"[1efaf3b8-ca7c-4e6f-878f-102d9a7a92d9]","version":1}> but was:<{"id":"[cfa1a8b0-be6a-46b1-90f5-d2f6d230796a]","version":1}>

如您所见,两个 UUID 是不同的,从我在这个问题的第一个链接中读到的内容是,每次调用静态方法 UUID.randomUUID() 时它都应该返回相同的 UUID (存储在 TestJackRabbitService 类中的 uuid 变量中的那个...

我还尝试使用 doReturn 方法,如 this answer 中所述但它会产生以下堆栈跟踪:

testAddDocumentsByJson(com.optimissa.test.junit.TestJackRabbitService)  Time elapsed: 5.279 sec  <<< ERROR!
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.optimissa.test.junit.TestJackRabbitService.testAddDocumentsByJson(TestJackRabbitService.java:143)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:182)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:164)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:134)
at com.optimissa.test.junit.TestJackRabbitService.testAddDocumentsByJson(TestJackRabbitService.java:143)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:149)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:132)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

来自 this answer我读到(但我不明白)也许我需要从我要测试的类中创建一个新对象?我在测试类的一开始就注入(inject)了依赖项,我对 JUnit 测试真的很陌生,英语不是我的母语,但是我能理解大部分内容,但答案是我很难理解它(由于我缺乏 JUnit 测试知识)。

如何使我的 JUnit 测试检索在方法内部生成的相同 ID(或拦截对 UUID.randomUUD() 的调用以返回值在我的 JUnit 测试中)?


编辑

尝试@hammerfest 的回答后,进行了以下更改:

UUID uuid = PowerMockito.mock(UUID.class);

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

String jsonToCompare = "{\"id\":\"" + uuid + "\",\"version\":1}";
String jsonFromJRS = jackRabbitService.addDocumentByJson(nameFile, bytes, nameApp, 5, jsonproperties);

assertEquals(jsonFromJRS, jsonToCompare);

我仍然得到这个结果:

testAddDocumentsByJson(com.optimissa.test.junit.TestJackRabbitService): expected:<{"id":"[493410b3-dd0b-4b78-97bf-289f50f6e74f]","version":1}> but was:<{"id":"[00000000-0000-0000-0000-000000000000]","version":1}>

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com