我们如何将模拟的viewModel注入到Activity中以进行浓缩咖啡测试?
使用package ShapesPackage;
public class Test {
public static void main(String[] args) {
Rectangle r = new rectangle();
System.out.println(r.perimeter());
System.out.println(r.semiPerimeter());
RightTriangle t = new rightTriangle();
System.out.println(t.perimeter()); //Fails
}
}
我在Test类中获得了模拟对象,但是Activity收到了常规的viewModel对象。
declareMock
答案 0 :(得分:0)
在这种情况下,Espresso测试仍在使用主应用程序类,该类声明了应用程序所需的所有@RunWith(AndroidJUnit4::class)
class SomeActivityTest : KoinTest {
@Rule
@JvmField
val rule = ActivityTestRule(SomeActivity::class.java, true, true)
val viewModel: MyViewModel by inject()
@Before
fun setup() {
declareMock<MyViewModel>(isFactory = true, binds = listOf(ViewModel::class))
}
@After
fun cleanUp() {
stopKoin()
}
@Test
fun shouldHaveTextViewVisible() {
`when`(viewModel.sayHello())
.thenReturn("hello view-model")
onView(withId(R.id.tv_homescreen_message))
.check(matches(isDisplayed()))
onView(withId(R.id.tv_homescreen_message))
.check(matches(withText("hello view-model")))
}
}
模块。
在没有任何模块的情况下开始koin
可使我们在测试期间仅加载所需的模块。
koin
在开始活动之前声明模拟方法很重要
// application class for espresso tests
class TestApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin(this, emptyList())
}
}
class TestAppJUnitRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
return super.newApplication(cl, TestApp::class.java.name, context)
}
}
// app module build.gradle
android {
defaultConfig {
testInstrumentationRunner "com.package.TestAppJUnitRunner"
}
}