簡體   English   中英

如何為擴展異常類的BusinessException創建存根

[英]How to create a stub for BusinessException which extends Exception class

我正在嘗試為異常類創建存根以返回一些字符串,但它不返回該字符串值。

java.lang.Exception: Unexpected exception, expected<ServiceException> but was<java.lang.NullPointerException>

這是我使用的示例代碼

BusinessException mockBusinessException =mock(BusinessException.class);

@Test(expected = ServiceException.class)
    public void testValidateForRegistrationError() throws ServiceException, BusinessException{
        when(ChecksUtil.initiateValidation(any(Request.class), any(Content.class))).thenThrow(BusinessException.class);
        when(mockBusinessException.getMessage()).thenReturn("Error");
        facadeBeanTest.createRegistration(RegistrationFacadeMock.getCreateRegistrationRequest());
    }

BusinessException extends Exception

可測試的類

public class FacadeBean{
    createRegistration(){
        try{
        }catch (BusinessException e) {
            String err = e.getMessage(); -- Failed in this line(null pointer exception)
            if(err.contains("Error") ){
                throw new ServiceException(ServiceErrorConstants.CATALOG_NAME, err);            
            }
        }

    }
}

那有什么遺漏嗎?有人建議。

在評論中解決:

為什么要嘲笑異常? 為什么真正的BusinessException無法正常工作?

為什么使用thenThrow(BusinessException.class)而不是thenThrow(mockBusinessException)

OP的評論, user3123934

這樣做之后解決了when(ChecksUtil.initiateValidation(any(Request.class),any(Content.class)))。thenThrow(new BusinessException(“ Error”));


當依賴關系很少且可靠的實現時,使用真實對象而不是模擬通常很有意義。 如果您確實使用了模擬,請通過在構造函數,模擬或重寫方法中提供模擬實例,確保被測系統在必要時使用模擬實例。

暫無
暫無

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

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