views:

77

answers:

3

Hi! I need mock some class with final method using mockito. I have wrote something like this

@Test
public void test() {
    B b = mock(B.class);
    doReturn("bar called").when(b).bar();   
    assertEquals("must be \"overrided\"", "bar called", b.bar());
    //bla-bla
}


class B {
    public final String bar() {
        return "fail";
    }
}

But it fails. I tried some "hack" and it works.

   @Test
   public void hackTest() {
        class NewB extends B {
            public String barForTest() {
                return bar();
            }
        }
        NewB b = mock(NewB.class);
        doReturn("bar called").when(b).barForTest();
        assertEquals("must be \"overrided\"", "bar called", b.barForTest());
    }

It works, but "smells".

So, Where is the right way?

Thanks.

+1  A: 

As Jon Skeet commented you should be looking for a way to avoid the dependency on the final method. That said, there are some ways out through bytecode manipulation (e.g. with PowerMock)

A comparison between Mockito and PowerMock will explain things in detail.

iwein
@iwein: Thanks. I'll read it.
Stas
A: 

From the Mockito FAQ:

What are the limitations of Mockito

  • Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.
matt b
A: 

Isnt this question a duplicate of http://stackoverflow.com/questions/190597/how-to-go-about-mocking-a-class-with-final-methods ?

Cshah
Similar, but not a duplicate. This question is coming from the viewpoint of Mockito, the other question is coming from a more general angle (unrelated to Mockito).
iwein