Android JUnit4 初心者導入用のサンプル]]というのを以前書きましたが、今回は、[[Espressoというフレームワークを使ったJUnitのテストを作ります。
前置きですが、自分自身初心者なので、「初心者用のサンプル」とはいささかおこがましいですが(^_^)、何か間違いがあれば、訂正していってください┌o ペコッ
まずは、gradle。
いっつもねー ここで必ず一波乱ある…。
もれなく今回も。
今回の問題は、該当のアプリのtargetSdkのバージョンを、22にしていたことです。
どうしても、22のままでは、espressoを読み込めなかった…orz
なので、targetSdkのバージョンを、23にしました。
下記のサイトのほぼコピペですが、appのレベルのbuild.gradleを次のように編集します。
https://developer.android.com/training/testing/start/index.html?hl=ja#config-instrumented-tests
dependencies {
androidTestCompile 'com.android.support:support-annotations:23.0.1'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
// Optional -- Hamcrest library
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
// Optional -- UI testing with Espresso
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
// Optional -- UI testing with UI Automator
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
}
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
んで、次の問題。
@RunWith(AndroidJUnit4.class)
が
Cannot resolve symbol 'AndroidJUnit4'
で読み込めない。
もちろん、espressoさんも
import static android.support.test.espresso.Espresso.onView;
が
Cannot resolve symbol 'espresso'
で読み込めない。。。
これに結構はまりましたが、正解は、テスト用のコードの置き場所が違っていたのでした…。
app\src\testの下ではなく、app\src\androidTestの下にテストコードを置かないとダメなのです。

このあたり、どっかの設定とかで変更できるのかなー
よくわかりません。
で、やーっとテストできるかと思いきや!
上記の図にある、RegisterActivityTest.javaを右クリックして、Run RegisterActivityTestを押しても、
Class not found: "jp.onlineconsultant.hogehoge.RegisterActivityTest"Empty test suite.
となってしまい、テストできません。(つД`)
これも、jp.onlineconsultant.hogehogeのディレクトリのところを右クリックして、Run Tests in と書いてあるのをクリックすると、テストができます。
さあてさて、RegisterActivityTest.javaはこんな感じです。
初心者用の超シンプルなサンプルですので、ご容赦を。
@RunWith(AndroidJUnit4.class)
@LargeTest
public class RegisterActivityTest {
private RegisterActivity mRegisterActivity = null;
private Button mRegisterButton;
private EditText mLast_name_box;
@Rule
public ActivityTestRule<RegisterActivity> mActivityRule = new ActivityTestRule<>(
RegisterActivity.class);
@Before
public void setUp(){
onView(withId(R.id.register_button)).check(matches(withText("送信")));
}
//テストが動作するかだけの確認用
@Test
public void testGetCrowd() {
Assert.assertEquals(1, 1);
}
}
