How to mock a String using mockito?

后端 未结 15 1746
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 00:22

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 achie

15条回答
  •  抹茶落季
    2021-02-05 00:59

    If you can use JMockit, look at Rogério answer.

    If and only if your goal is to get code coverage but not actually simulate what missing UTF-8 would look like at runtime you can do the following (and that you can't or don't want to use JMockit):

    public static String f(String str){
        return f(str, "UTF-8");
    }
    
    // package private for example
    static String f(String str, String charsetName){
        try {
            return new String(str.getBytes(charsetName));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Unsupported encoding: " + charsetName, e);
        }
    }
    
    public class TestA {
    
        @Test(expected=IllegalArgumentException.class)
        public void testInvalid(){
            A.f(str, "This is not the encoding you are looking for!");
        }
    
        @Test
        public void testNormal(){
            // TODO do the normal tests with the method taking only 1 parameter
        }
    }
    

提交回复
热议问题