vendredi 31 mai 2019

Stubbing out method with ArrayList/List param fails when using any() or anyList()

I have a java class that I am trying to test:

class Blah{
        public Blah(){

        }
        public String testMe(List<String> s){
            return new String("hello "+s.get(0));
        }


        public String testMeString(String s){
            return new String("hello "+s);
        }


    }

I am unable to test the testMe method successfully. For example I have tried:

    @Test
    public void testTestMe(){
        Blah blah = spy(new Blah());
        ArrayList<String> l = new ArrayList<String>();
        l.add("oopsie");
        when(blah.testMe(Matchers.any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMe(l));

This returns a NullPointerException. I have also tried any(List.class), any(ArrayList.class). I have also tried using anyList() but this gives me an IndexOutOfBounds error. What am I doing wrong? Interestingly, my testMeString works fine. If I do

@Test
    public void testTestMeString(){
        Blah blah = spy(new Blah());
        when(blah.testMeString(any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMeString("lala"));
}

the tests pass with any() and any(String.class).

Aucun commentaire:

Enregistrer un commentaire