Mocking method before activity is created? - android

I am using Espresso and Mockito for testing an Activity. Is it possible to mock a method before an activity is created.
public class MyActivity extends Activity {
public int i;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callSomeMethod();
callAnotherMethod();
}
protected void callSomeMethod() {
//do some work
}
protected void callAnotherMethod() {
//do some work
}
}
My test class looks like
public class ActivityTest{
#Rule
public MyActivityRule testRule = new MyActivityRule(MyActivity.class);
public void test_preconditions(){
assertNotNull(testRule.getActivity())
}
}
But i need to mock callSomeMethod() and callAnotherMethod() method. Thanks in advance.

Related

How to write an app with repetitive parts?

I want to write an app with about 20 different Activity. Inside each activity there is some parts that are similar in some other activities. I divided each page to smart parts and write a separate layout for them. Then in activities I use include tag for adding that part to activity.
I don't know what is the true way to implement this app.
Thanks for any suggestion.
I have made sample BaseActivity. Make abstract method you want to use and just override to your class. You can use all Base Activity public method in your class. abstract method will override to your class and simple Public method will be optional if you want to use
public abstract class BaseMainActivity extends AppCompatActivity implements View.OnClickListener{
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initMethod();
setContentView(getLayout());
initUI();
initListeners();
}
public abstract void initMethod();
public abstract int getLayout();
public abstract void initUI();
public abstract void initListeners();
#Override
public void onClick(View view) {
}
public String getEditString(CustomEdittext edittext){
return edittext.getText().toString().trim();
}
public void getEditError(CustomEdittext edittext, String message){
edittext.setError(message);
}
public static void showProgress(AppCompatActivity activity){
try{
progressDialog = new ProgressDialog(activity);
progressDialog.setTitle("Please Wait");
progressDialog.show();
}catch (Exception ex){
ex.printStackTrace();
}
}
public static void hideProgress(){
try{
if(progressDialog!=null)
progressDialog.dismiss();
}catch (Exception ex){
ex.printStackTrace();
}
}
public void showToast(String message,Context context)
{
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
}
Hi this is sample that we can extend BaseActivity to our class.
public class HomeActivity extends BaseMainActivity {
private Toolbar toolbar = null;
private Picasso picasso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void initMethod() {
}
#Override
public int getLayout() {
return R.layout.activity_main;
}
#Override
public void initUI() {
initToolbar();
initDrawerLayout();
initNavigationView();
}
}
You can create base activity for similar methods and extend it in other activities.
And about layouts you can create similar layouts at first then include them to other layouts.
And for good structure i think use MVP.

Butterknife + Espresso NoMatchingViewException

Can Butterknife work with Espresso? I have a test sample, there are 2 activities. In the first activity I print the text, than click the button and send text to another activity. After that I created MainActivityTest and everything worked well. But when I started to use Butterknife I caught the error NoMatchingViewException.
My first activity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.first_text)
EditText mEditText;
#OnClick(R.id.button_one)
public void click(){
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("TEXT",mEditText.getText().toString());
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The second activity:
public class SecondActivity extends AppCompatActivity {
public static final String TAG = SecondActivity.class.getSimpleName();
#BindView(R.id.second_text)
TextView mTextView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
#Override
protected void onResume() {
super.onResume();
if(getIntent().getStringExtra("TEXT")!=null) {
mTextView.setText(getIntent().getStringExtra("TEXT"));
}
}
}
My MainActivityTest:
public class MainActivityTest {
#Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
MainActivity.class);
#Before
public void setUp() throws Exception {
}
#Test
public void onCreate() throws Exception {
onView(withId(R.id.first_text)).perform(typeText("Test"));
onView(withId(R.id.button_one)).perform(click());
onView(withId(R.id.second_text)).check(matches(withText("Test")));
}
}

Find Id of View in Child Activity

I have an issue , need your help , my question is : I have a multiple activity , so i have created one abstract class which hold the view . Now my question i am able to pass the view to the Base Activity but how to finds view id in Child Activity Class.
I Tried like this :
public abstract class BaseActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
}
public abstract int getLayoutResourceId();
}
My Activity Class:
public class ServiceActivity extends BaseActivity {
Button startSerice_btn, stopService_btn;
MyService myService;
#Override
public int getLayoutResourceId() {
return R.layout.service_xml;
}
}
You can access your views after the super.onCreate() call in the ServiceActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Access them here
}
I think you no need to set content view in BaseActivity like below :
public abstract class MyAppBaseActivity extends AppCompatActivity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And you just extends Activity like below :
// for MyCustomActivity1
public class MyCustomActivity1 extends MyAppBaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onClick(View view) {
}
}
// for MyCustomActivity2
public class MyCustomActivity2 extends MyAppBaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onClick(View view) {
}
}

Put common listeners inside MainActivity class

Im interested if i can to set some common listeners inside main activity class? For my project i use FirebaseAuth, so i would like to init it in MainActivity onCreate(), setup needed listeners in onStart() and onStop(), and then inherit that class in every other activity class.
Some code to please you :]
MainActivity class [parent]:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
protected FirebaseAuthentication firebaseAuthentication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firebaseAuthentication = new FirebaseAuthentication(FirebaseAuth.getInstance(), FirebaseDatabase.getInstance());
}
#Override
protected void onStart() {
super.onStart();
firebaseAuthentication.addAuthStateListener();
}
#Override
public void onStop() {
super.onStop();
firebaseAuthentication.removeAuthStateListener();
}
}
AuthActivity class [child]:
public class AuthActivity extends MainActivity implements FirebaseAuthentication.OnUserAuthListener {
#BindView(R.id.viewPager) LockableViewPager viewPager;
private String userUID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_market);
ButterKnife.bind(this);
firebaseAuthentication.setOnUserAuthListener(this);
firebaseAuthentication.isSingedIn(); // check if user is singed in
}
#Override
// response for firebaseAuthentication.isSingedIn() above
public void onAuthSuccess(String userUID) {
this.userUID = userUID;
}
#Override
// response for firebaseAuthentication.isSingedIn() above
public void onAuthFailure(String message) {
snackbar(message);
Intent intent = new Intent(this, AuthActivity.class);
startActivity(intent);
finish(); // TODO mb should to delete it
}
}
Can this implementations bring me errors (maybe NullPointerExeption or what unexpectedly in future)?
Would be great if you provide me some sources to read/watch.
Thank you.
Perfect example of abstraction, but not really a question.
You will not get any nullpointers or other errors by implementing it like this.

Android can not cast Context to Activity

I have a class which extends Activity.
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id,someactivitylayout);
new Game(getApplicationContext());
}
My Game class looks like
public class Game{
Game(final Context context){
cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* here i need to call runOnUIThread*/
}
}
}
My code does not have any syntax errors, so it compiles fine.
In the place where i have to call runOnUIThread, i have tried
Thread t = new Thread() {
public void run() {
while (progressBar.getProgress() < 100) {
((Activity) context).runOnUiThread(new unnable() {
public void run() {
}
});
}
};
t.start();
But when i try to cast context to Activity it gives an exception
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
Why is it not possible to cast context to Activity??
I have tried many ways but did not find anyway to get Activity in my Game class.
Is there any way to do that??
You are sending ApplicationContext to the Game class. Just replace the getApplicationContext() with this to pass the Activity Context. It will work.
It should be new Game(this)
try with
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id,someactivitylayout);
new Game(this);
}
}

Categories

Resources