测试该按钮可使用 Robolectric 启动活动
您好,我有以下代码:
@RunWith(Test9Runner.class)
public class MainActivityTest
{
private MainActivity activity;
private Button pressMeButton;
@Before
public void setUp() throws Exception
{
activity = new MainActivity();
activity.onCreate(null);
pressMeButton = (Button) activity.findViewById(R.id.button1);
}
@Test
public void shouldUpdateResultsWhenButtonIsClicked() throws Exception
{
pressMeButton.performClick();
ShadowActivity shadowActivity = shadowOf(activity);
Intent intent = shadowActivity.getResultIntent();
System.out.print(intent.toString());
}
}
但我不知道如何测试按下 pressMeButton 启动一个新的活动。事实上确实如此,但如何为此事实编写正确的 Robolectric 单元测试呢?
Hi I have the following code:
@RunWith(Test9Runner.class)
public class MainActivityTest
{
private MainActivity activity;
private Button pressMeButton;
@Before
public void setUp() throws Exception
{
activity = new MainActivity();
activity.onCreate(null);
pressMeButton = (Button) activity.findViewById(R.id.button1);
}
@Test
public void shouldUpdateResultsWhenButtonIsClicked() throws Exception
{
pressMeButton.performClick();
ShadowActivity shadowActivity = shadowOf(activity);
Intent intent = shadowActivity.getResultIntent();
System.out.print(intent.toString());
}
}
But I have no idea how to test that pressing pressMeButton started a new Activity. Actually it does, but how to write the correct Robolectric unit test for this fact?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 Robolectric 2.1.1 中,您可以验证启动新
Activity
的Intent
是否通过以下方式发出。这与我正在做的事情类似。
请注意,通过调用
new Activity()
创建Activity
将使 Robolectric 打印有关创建活动不当的警告,这可能可以做得更好......In Robolectric 2.1.1 you can verify if
Intent
starting newActivity
was emitted in following way.This is similar to what I am doing.
Please note that creating
Activity
by callingnew Activity()
will make Robolectric print warnings about creating activity improperly, this probably can be done better...将其更新为 3.1.2,因为上面的答案对我不起作用:-
Updating this for 3.1.2 as the answers above did not work for me:-
使用 Robolectric 的
StartedMatcher
Use Robolectric's
StartedMatcher
受到 @MichK 答案的启发,这里是使用 Robolectric 2.2+ 中的
buildActivity
方法链进行的完整运行测试:Inspired by @MichK's answer, here is a complete running test using the
buildActivity
method chain from Robolectric 2.2+:James Neville 的答案适用于 4.3。不过,我使用了 AndroidX API、Espresso 和 Kotlin:
James Neville's answer works on 4.3. However, I used the AndroidX API, Espresso and Kotlin:
这就是 Robolectric 3 的样子
This is how does it looks like for the Robolectric 3