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);
}
@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.
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.
@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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With