How to mock a String using mockito?

后端 未结 15 1789
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    2021-02-05 01:03

    You can change your method to take the interface CharSequence:

    public final class A {
        public static String f(CharSequence str){
            try {
                return new String(str.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // This is the catch block that I want to exercise.
                ...
            }
        }
    }
    

    That way, you can still pass in String, but you can mock any way you like.

提交回复
热议问题