Mockar non-static method of a class containing a call from another static method

1

Hello,

The title was a bit confusing, but come on. I have the class below:

public class ClasseA {

    public static final int constA = ClasseB.metodoB();


    public int metodoA(){
        System.out.println("Passei no metodo A");
        return 2;
    }
}

I would like to mock methodA, but I can not because it always calls method B.

My Test Class:

public class TestesClasses {

    @Mock
    private ClasseA classeA;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testando(){
        Mockito.when(classeA.metodoA()).thenReturn(1);

        int retorno = classeA.metodoA();
        System.out.println("Retorno "+retorno);
    }
}

I want to be mockado tmb method B, as if I wanted to mock almost the entire class. I already tried with mockito, powermock, etc and it does not work ... If anyone can help me and put it as did the test class, thank you very much !!!!

    
asked by anonymous 15.01.2018 / 11:41

1 answer

1

I was able to find the solution.

As he was calling the method before, I put a @BeforeClass as below:

@RunWith(PowerMockRunner.class)
@PrepareForTest( { ClasseA.class,ClasseB.class })
public class TestesClasses {

    @Mock
    private ClasseA classeA;

    @BeforeClass
    public static void setUp(){
        PowerMockito.mockStatic(ClasseB.class);
        Mockito.mock(ClasseA.class);
    }

    @Test
    public void testando(){
        PowerMockito.when(ClasseB.metodoB()).thenReturn(5);     
        Mockito.when(classeA.metodoA()).thenReturn(1);

        int retornoA = classeA.metodoA();
        int retornoB = ClasseB.metodoB();
        System.out.println("Retorno A: "+retornoA);
        System.out.println("Retorno B: "+retornoB);
    }
}
    
15.01.2018 / 12:12