mockito 如何修复java.lang.IllegalStateException:无法展开代理对象错误

b0zn9rqh  于 2023-10-18  发布在  Java
关注(0)|答案(1)|浏览(134)

我有这个示例实现和测试,但我得到的错误

java.lang.IllegalStateException: Failed to unwrap proxied object
...
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 is completed
...
...

@Service
public class FirebaseService {
    ...

    public FirebaseService(...) {
        ...
    }

    public FirebaseApp initializeApp() {

        try {
            ...
            InputStream inputStream = getServiceAccountFileInputStream();
            ...
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public InputStream getServiceAccountFileInputStream() throws IOException {
        ...
    }
}

...

@ExtendWith(SpringExtension.class)
@RunWith(SpringRunner.class)
@SpringBootTest
public class FirebaseServiceTest {

    ...
    @Autowired
    private FirebaseService firebaseService;
    ...

    @Test
    public void whenGetAppIsEmpty_thenReturnFirebaseAppInstanceFromInitializeApp() throws IOException {
        ...
        InputStream inputStream = mock(InputStream.class);
        ...
        FirebaseService firebaseServiceSpy = spy(firebaseService);

// Specifically at this point       
doReturn(FileInputStream.nullInputStream()).when(firebaseServiceSpy).getServiceAccountFileInputStream();
        ...
    }
}

我是新的测试,所以我感谢任何人的帮助,可以帮助我认识到我做错了什么。谢谢你
我试着像这样监视自动连接的依赖关系,我希望该方法返回空输入流...

...
FirebaseService firebaseServiceSpy = spy(firebaseService);
doReturn(FileInputStream.nullInputStream()).when(firebaseServiceSpy).getServiceAccountFileInputStream();
...
erhoui1w

erhoui1w1#

我在目标服务上使用了@SpyBean注解,如下所示

...
    @Autowired
    @SpyBean
    private FirebaseService firebaseService
    ...

    ...
    doReturn(...).when(firebaseService).doSomething();
    ...

相关问题