2016-05-10 13 views
5

Tôi cần thử nghiệm một hoạt động trong ứng dụng Android của mình. Tài liệu của ActivityInstrumentationTestCase2 nói:ActivityInstrumentationTestCase2 vs ActivityTestRule

Lớp này cung cấp thử nghiệm chức năng của một hoạt động đơn lẻ.

Và tài liệu của ActivityTestRule nói:

Quy tắc này cung cấp thử nghiệm chức năng của một hoạt động đơn lẻ.

Hầu như cùng một từ. Bên cạnh hai mẫu tôi đã mã hóa, làm tương tự. Vì vậy, tôi có nên thích ActivityTestRule hơn ActivityInstrumentationTestCase2 hoặc ngược lại không?

Điều tôi thấy là mở rộng ActivityInstrumentationTestCase2 trông giống như kiểm tra kiểu JUnit3 (tổ tiên của nó là junit.framework.TestCase và phương pháp thử phải bắt đầu bằng từ test).

Sử dụng ActivityTestRule

package sample.com.sample_project_2; 

import android.support.test.rule.ActivityTestRule; 
import android.support.test.runner.AndroidJUnit4; 
import android.test.suitebuilder.annotation.LargeTest; 

import org.junit.Rule; 
import org.junit.Test; 
import org.junit.runner.RunWith; 

import static android.support.test.espresso.Espresso.onView; 
import static android.support.test.espresso.action.ViewActions.typeText; 
import static android.support.test.espresso.matcher.ViewMatchers.withId; 

@RunWith(AndroidJUnit4.class) 
@LargeTest 
public class ApplicationTest { 

    @Rule 
    public ActivityTestRule<SecAct> mActivityRule = new ActivityTestRule(SecAct.class); 

    @Test 
    public void foo() { 
     onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE")); 

    } 
} 

Mở rộng ActivityInstrumentationTestCase2

package sample.com.sample_project_2; 

import android.test.ActivityInstrumentationTestCase2; 

import static android.support.test.espresso.Espresso.onView; 
import static android.support.test.espresso.action.ViewActions.typeText; 
import static android.support.test.espresso.matcher.ViewMatchers.withId; 


public class ApplicationTest2 extends ActivityInstrumentationTestCase2<SecAct> { 

    public ApplicationTest2() { 
     super(SecAct.class); 
    } 

    @Override 
    protected void setUp() throws Exception { 
     super.setUp(); 
     getActivity(); 
    } 


    public void testFoo2() { 
     onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE 2")); 

    } 
} 

Trả lời

1

Ví dụ của bạn, không có sự khác biệt. Bạn có thể sử dụng bất kỳ trong số họ.

Theo nguyên tắc OO, chúng tôi sẽ "Ưu tiên thành phần trên thừa kế". Việc sử dụng ActivityTestRule<> là thông qua bố cục trong khi ActivityInstrumentationTestCase2<> là mặc dù được thừa kế.

Đôi khi, tôi muốn có một lớp cơ sở chung cho các lớp thử nghiệm của mình để sử dụng lại các khởi tạo chung. Điều này giúp tôi nhóm các bài kiểm tra theo một chủ đề. ActivityTestRule<> cho phép tôi làm những việc như vậy.

Vì những lý do này, tôi thích ActivityTestRule<>. Nếu không, tôi đã không thấy bất kỳ sự khác biệt nào.

Các vấn đề liên quan