Using Mockito to mock a class method inside another class

后端 未结 3 1380
陌清茗
陌清茗 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:37

    This Worked for Me:

    public class Class1Test {
    
      Class1 class1;
    
      @Before
      public void setUp() {
        MockitoAnnotations.initMocks(this);
        class1 = new Class1();
      }
    
      @Test
      public void testClass1Method() {
    
        Class2 class2 = Mockito.mock(Class2.class);
        class1.setClass2(class2);
        Mockito.when(
                class2.class2Method(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("some response");
    
        String actualResponse = class1
                .class1Method("12345", "3333", "4444");
        assertEquals("some response", actualResponse);
      }
    }
    

提交回复
热议问题