这是我的活动片段:
public class Search extends Activity
{
private String TAG = "SEARCH";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
Log.d(TAG, "About to call initialastion");
// new InitialisationTask(this).execute();
}
}
有了上面的注释,我可以愉快地创建和执行单元测试,如下所示:
@RunWith(RobolectricTestRunner.class)
public class SearchTest {
private Search searchActivity;
private Button searchButton;
private Button clearButton;
private Button loginButton;
private Button registerButton;
private EditText searchEditText;
@Before
public void setUp() throws Exception {
searchActivity = new Search();
searchActivity.onCreate(null);
searchButton = (Button) searchActivity.findViewById(R.id.btnPlateSearch);
clearButton = (Button) searchActivity.findViewById(R.id.btnClearSearch);
loginButton = (Button) searchActivity.findViewById(R.id.btnLogin);
registerButton = (Button) searchActivity.findViewById(R.id.btnRegister);
searchEditText = (EditText) searchActivity.findViewById(R.id.editTextInputPlate);
}
@Test
public void assertSearchButtonHasCorrectLabel()
{
assertThat((String) searchButton.getText(), equalTo("Search"));
}
}
但是,如果我new InitialisationTask(this).execute();
在我的活动中取消注释该行,我的测试开始失败,很可能是因为对this
.
模拟上下文的最佳方法是什么?
我试图添加contextMock = mock(Context.class);
到我的setUp()
但是我不确定如何将这个模拟设置为“进入”searchActivity
谢谢