[英]Mockito mocking a function call in an if statement
我正在嘗試模擬對駐留在if
語句中的外部api的函數調用。 我無法返回.thenReturn
的值,並且不確定為什么。 我一直在尋找有關此問題的答案,但似乎找不到任何能回答我問題的答案。 感謝您的寶貴時間!
這是我正在測試的班級:
@Service
public class TwilioVerifyService {
public String requestCode(String phoneNumber, String countryCode, String via) throws AuthyException
{
AuthyApiClient authyApiClient = new AuthyApiClient("<apiClient>");
Params params = new Params();
params.setAttribute("code_length", "6");
Verification verification = authyApiClient
.getPhoneVerification()
.start(phoneNumber, countryCode, via, params);
if (verification.isOk())
{
return "{ \"success\": \"Successfully sent verification code.\" }";
}
return "{ \"error\": \"Error sending code.\" }";
}
}
這是我的測試:
@RunWith(MockitoJUnitRunner.class)
public class TwilioVerifyServiceTests {
@InjectMocks
TwilioVerifyService twilioVerifyService;
@Mock
Verification verification;
@Test
public void requestCodeTest_success() throws AuthyException
{
String phoneNumber = "1111111111";
String countryCode = "1";
String via = "1";
when(verification.isOk()).thenReturn(true);
String result = twilioVerifyService.requestCode(phoneNumber, countryCode, via);
System.out.println(result);
}
}
我相信我正在(或希望成為)模擬出verification.isOk()
不論輸入如何都返回true,但是如果提供"{ "error": "Error sending code." }"
而不是"{ \\"success\\": \\"Successfully sent verification code.\\" }"
,它似乎返回false "{ "error": "Error sending code." }"
"{ \\"success\\": \\"Successfully sent verification code.\\" }"
。
感謝你的寶貴時間!
驗證是通過對AuthyApiClient中的方法的調用生成的。
理想情況下,不應在您的服務中實例化AuthyApiClient,而應由調用者將其注入其中。
private AuthyApiClient authyApiClient;
@Autowired
public TwilioVerifyService(AuthyApiClient authyApiClient) {
this.authyApiClient = authyApiClient;
}
然后,您可以模擬authyApiClient並將其傳遞給要測試的類:TwilioVerifyService twilioVerifyService = new TwilioVerifyService(mockAuthyApiClient);
這使您可以更好地控制要測試的類,並刪除其當前對AuthyApiClient構造函數的依賴關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.