如何模拟应用程序上下文

时间:2017-06-01 10:30:33

标签: java android unit-testing mockito

我们如何模拟应用程序上下文?我有一位演示者,我打算为他写一个测试。它收到的参数是vie w和Context。如何为上下文创建模拟工作?

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);
}

1 个答案:

答案 0 :(得分:4)

作为基础,我会使用Mockito注释(我假设你也想模拟视图):

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...)
   }

}

此wold注入准备好将mocks配置到您正在测试的类中。