How to mock a String using mockito?

后端 未结 15 1751
佛祖请我去吃肉
佛祖请我去吃肉 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 01:15

    Have you tried passing an invalid charsetName to getBytes(String)?

    You could implement a helper method to get the charsetName, and override that method within your test to a nonsense value.

    0 讨论(0)
  • 2021-02-05 01:16

    How about just creating a String with a bad encoding name? See

    public String(byte bytes[], int offset, int length, String charsetName)
    

    Mocking String is almost certainly a bad idea.

    0 讨论(0)
  • 2021-02-05 01:19

    It is a project requirement that the unit tests coverage percentage must but higher than a given value. To achieve such percentage of coverage the tests must cover the catch block relative to the UnsupportedEncodingException.

    What is that given coverage target? Some people would say that shooting for 100% coverage isn't always a good idea.

    Besides, that's no way to test whether or not a catch block was exercised. The right way is to write a method that causes the exception to be thrown and make observation of the exception being thrown the success criterion. You do this with JUnit's @Test annotation by adding the "expected" value:

    @Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
       new ArrayList<Object>().get(1);
    }
    
    0 讨论(0)
提交回复
热议问题