簡體   English   中英

Spring Data JPA findById()拋出ClassCastException

[英]Spring Data JPA findById() throwing ClassCastException

我有一個使用Spring Data JPA的findById()方法的方法。 但是,此方法在getSupportedKey()方法的第1行返回ClassCastException ,我在其中調用findById():

MySupportedKey cannot be cast to java.util.Optional

private MySupportedKey getSupportedKey(String tenant, String key) {
        Optional<MySupportedKey> mySupportedKeyOptional = mySupportedKeyRepository.findById(new MySupportedKeyId(tenant, key));
        MySupportedKey mySupportedKey= null;
        if(mySupportedKeyOptional !=null) {
             mySupportedKey= mySupportedKeyOptional.orElse(null);
        }
        return mySupportedKey;
    }

我一直在打我的頭很長一段時間,但我沒有得到任何東西。 請幫我解決這個問題。 我使用的是spring-data-jpa:2.0.8.RELEASE

添加存儲庫源代碼:

public interface MySupportedKeyRepository extends JpaRepository<MySupportedKey, MySupportedKeyId> {

List<MySupportedKey> findByIdTenant(@NotNull String tenant);
}

添加完整的堆棧錯誤跟蹤:

java.lang.ClassCastException: com.test.service.user.entity.MySupportedKey cannot be cast to java.util.Optional
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock$1304362870.findById(Unknown Source)
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock$1304362870.findById(Unknown Source)
at com.test.service.user.userpreferences.PreferencesServiceImpl.getSupportedKey(PreferencesServiceImpl.java:217)
at com.test.service.user.userpreferences.PreferencesServiceImpl.updateUserPreferences(PreferencesServiceImpl.java:167)
at com.test.service.user.userpreferences.PreferencesServiceImpl.lambda$2(PreferencesServiceImpl.java:92)
at java.util.ArrayList.forEach(Unknown Source)
at com.test.service.user.userpreferences.PreferencesServiceImpl.updateUserPreferences(PreferencesServiceImpl.java:92)
at com.test.service.user.preferences.PreferencesServiceImplTest.updateUserPreferences(PreferencesServiceImplTest.java:300)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.mockito.internal.junit.JUnitRule$1.evaluateSafely(JUnitRule.java:52)
at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:43)
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.RunPrepareTestInstanceCallbacks.evaluate(RunPrepareTestInstanceCallbacks.java:64)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.statements.SpringFailOnTimeout.evaluate(SpringFailOnTimeout.java:87)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.statements.ProfileValueChecker.evaluate(ProfileValueChecker.java:103)
at org.springframework.test.context.junit4.rules.SpringClassRule$TestContextManagerCacheEvictor.evaluate(SpringClassRule.java:230)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

您為存儲庫設置了Mockito模擬,並可能告訴它在調用findById時返回MySupportedKey實例。 但是因為findById應該返回一個Optional你現在得到了異常。

您可以看到這是來自堆棧跟蹤的前兩行中的Mockito。

java.lang.ClassCastException: com.test.service.user.entity.MySupportedKey cannot be cast to java.util.Optional
at com.test.service.user.repository.MySupportedKeyRepository$MockitoMock$1304362870.findById(Unknown Source)

修改以下方法中的Optional處理以獲得如下所示的正確表示:

private MySupportedKey getSupportedKey(String tenant, String key) {
            Optional<MySupportedKey> mySupportedKeyOptional = mySupportedKeyRepository.findById(new MySupportedKeyId(tenant, key));
            MySupportedKey mySupportedKey= null;
            if(mySupportedKeyOptional.isPresent()) {
                 mySupportedKey= mySupportedKeyOptional.get();
            }
            return mySupportedKey;
        }

無法添加評論,只是想詳細說明Jens的答案,因為我花了一段時間才弄清楚如何解決這個問題(成為新手)。 為了解決這個問題,我改變了我的代碼:

when(mongoRepository.findById(Mockito.anyString())).thenAnswer(new Answer<MongoObj>() {
        @Override
        public MongoObj answer(InvocationOnMock invocation) throws Throwable {
            MongoObj repush = new MongoObj();
            //Some other code

            return repush;
        }
    });

when(mongoRepository.findById(Mockito.anyString())).thenAnswer(new Answer<Optional<MongoObj>>() {
        @Override
        public Optional<MongoObj> answer(InvocationOnMock invocation) throws Throwable {
            MongoObj repush = new MongoObj();
            //Some other code

            return Optional.of(repush);
        }
    });

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM