Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock application context

How do we mock an Application Context? I got a presenter which I intend to write a test for. The parameters it receives were a view and Context. How do I create a mock for context to work?

public TutorProfilePresenter(TutorProfileScreenView view, Context context){
     this.view = view;
     this.context = context
}
            
public void setPrice(float price,int selectedTopics){
      int topicsPrice = 0;
      if(selectedTopics>2)
      {
        topicsPrice = (int) ((price/5.0)*(selectedTopics-2));
      }
                    
                    
      view.setBasePrice(price,topicsPrice,selectedTopics,
                        price+topicsPrice);
}
like image 369
Jay kishan Avatar asked Jun 01 '17 10:06

Jay kishan


People also ask

What is the difference between @mock and @MockBean?

@Mock is used when the application context is not up and you need to Mock a service/Bean. @MockBean is used when the application context(in terms of testing) is up and you need to mock a service/Bean.

Can I mock an interface?

We can use org. mockito. Mockito class mock() method to create a mock object of a given class or interface. This is really the simplest way to mock an object.

What is the difference between @mock and @InjectMocks?

@Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class. Annotated class to be tested dependencies with @Mock annotation.

How do you inject a mock in SpringBootTest?

If you want to create just a Mockito test you could use the annotation @RunWith(MockitoJUnitRunner. class) instead of @SpringBootTest . But if you want to create a Spring Boot integration test then you should use @MockBean instead of @Mock and @Autowired instead of @InjectMocks .


1 Answers

As a base I would use the Mockito annotations( i assume you want to mock the view also):

public class TutorProfilePresenter{

   @InjectMocks
   private TutorProfilePresenter presenter;

   @Mock
   private TutorProfileScreenView viewMock;
   @Mock
   private Context contextMock;

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

   @Test
   public void test() throws Exception{
      // configure mocks
      when(contextMock.someMethod()).thenReturn(someValue);

      // call method on presenter

      // verify
      verify(viewMock).setBasePrice(someNumber...)
   }

}

This would inject ready to configure mocks into your class under test.

More insight on Mockito stubbing: sourceartists.com/mockito-stubbing

like image 110
Maciej Kowalski Avatar answered Sep 24 '22 11:09

Maciej Kowalski