問題描述
我需要模擬一個測試場景,在該場景中我調用 String 對象的 getBytes()
方法并得到 UnsupportedEncodingException.
I need to simulate a test scenario in which I call the getBytes()
method of a String object and I get an UnsupportedEncodingException.
我已嘗試使用以下代碼來實現:
I have tried to achieve that using the following code:
String nonEncodedString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));
問題是,當我運行我的測試用例時,我得到一個 MockitoException,它說我無法模擬 java.lang.String 類.
The problem is that when I run my test case I get a MockitoException that says that I can't mock a java.lang.String class.
有沒有辦法使用 mockito 來模擬 String 對象,或者,當我調用 getBytes 方法時,是否可以讓我的 String 對象拋出 UnsupportedEncodingException?
Is there a way to mock a String object using mockito or, alternatively, a way to make my String object throw an UnsupportedEncodingException when I call the getBytes method?
這里有更多細節來說明問題:
Here are more details to illustrate the problem:
這是我要測試的類:
public final class A {
public static String f(String str){
try {
return new String(str.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// This is the catch block that I want to exercise.
...
}
}
}
這是我的測試類(我正在使用 JUnit 4 和 mockito):
This is my testing class (I'm using JUnit 4 and mockito):
public class TestA {
@Test(expected=UnsupportedEncodingException.class)
public void test(){
String aString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));
A.f(aString);
}
}
推薦答案
問題是Java中的String
類被標記為final,所以使用傳統的mocking框架不能mock.根據 Mockito FAQ,這也是該框架的限制.
The problem is the String
class in Java is marked as final, so you cannot mock is using traditional mocking frameworks. According to the Mockito FAQ, this is a limitation of that framework as well.
這篇關于如何使用 mockito 模擬字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!