Using Mockito to mock a class method inside another class

后端 未结 3 1391
陌清茗
陌清茗 2021-02-05 14:58

I\'m trying to write unit tests with Mockito / JUnit for a function like this:

class1 {
 method {
  object1 = class2.method // method that I want to fake the ret         


        
3条回答
  •  逝去的感伤
    2021-02-05 15:33

    I wrote a simple example which worked fine, hope it helps:

    method1() from Class1 calls method2() from Class2:

        public class Class1 {
            private Class2 class2 = new Class2();
            public int method1() {
                return class2.method2();
            }
        }
    

    Class2 and method2() :

        public class Class2 {
            public int method2() {
                return 5;
            }
        }
    

    And the Test:

        import org.junit.Rule;
        import org.junit.Test;
        import org.mockito.InjectMocks;
        import org.mockito.Mock;
        import org.mockito.junit.MockitoJUnit;
        import org.mockito.junit.MockitoRule;
    
        import static org.junit.Assert.assertEquals;
        import static org.mockito.Mockito.when;
    
        public class TestClass1 {
    
            @Mock
            Class2 class2;
    
            @InjectMocks
            Class1 class1;
    
            @Rule
            public MockitoRule mockitoRule = MockitoJUnit.rule();
    
            @Test
            public void testMethod1(){
                when(class2.method2()).thenReturn(29);
                assertEquals(29,class1.method1());
            }
        }
    

提交回复
热议问题