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

Asked

Viewed 587 times

1

Hello,

The title got a little fuzzy, 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 the method, but I cannot, because it always calls the B method.

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 mock tmb the B method, as if I wanted to mock almost the entire class. I’ve tried with mockite, powermock, etc and it doesn’t work... If anyone can help me and put how you did the test class, I really appreciate it!!!!

  • I don’t understand. You want the mock of the object of ClasseA? Or want to mock the static method of ClasseB?

  • I want to mock the Class A method, but when I declare: @Mock Private Classea classeA; it calls the method B... that tmb want to mock

  • 1

    Your question gave me this doubt: https://answall.com/q/269196/64969

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);
    }
}
  • marks that the answer solved the problem. Has a V below the up/down vote area to do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.