Mock class in class under test

后端 未结 3 1668
有刺的猬
有刺的猬 2020-12-30 02:10

How I can mock with Mockito other classes in my class which is under test?

For example:

MyClass.java

class MyClass {
    public boolean perfo         


        
相关标签:
3条回答
  • 2020-12-30 02:28

    You can set what to return in Mockito.

    when(mock.method()).thenReturn(someValue)
    
    0 讨论(0)
  • 2020-12-30 02:40

    You could refactor MyClass so that it uses dependency injection. Instead of having it create an AnythingPerformerClass instance you could pass in an instance of the class to the constructor of MyClass like so :

    class MyClass {
    
       private final AnythingPerformerClass clazz;
    
       MyClass(AnythingPerformerClass clazz) {
          this.clazz = clazz;
       }
    
       public boolean performAnything() {         
         return clazz.doSomething();        
       }
    }
    

    You can then pass in the mock implementation in the unit test

    @Test
    public void testPerformAnything() throws Exception {
       AnythingPerformerClass mockedPerformer = Mockito.mock(AnythingPerformerClass.class);
       MyClass clazz = new MyClass(mockedPerformer);
       ...
    }
    

    Alternatively, if your AnythingPerformerClass contains state then you could pass a AnythingPerformerClassBuilder to the constructor.

    0 讨论(0)
  • 2020-12-30 02:49

    As it currently is (both declaration and instantiation of the AnythingPerformerClass inside a method, it's not possible to mock the AnythingPerformerClass using only Mockito.

    If possible, move both the declaration and the instantiation of AnythingPerformerClass to the class level: declare an instance variable of type AnythingPerformerClass and have it instantiated by the constructor.

    That way, you could more easily inject a mock of AnythingPerformerClass during test, and specify its behaviour. For example:

    when(anythingPerformerClassMock.doSomething()).thenReturn(true);
    

    or to test error handling:

    when(anythingPerformerClassMock.doSomething()).thenTrow(new NullPointerException());
    
    0 讨论(0)
提交回复
热议问题