如何测试 Toast 消息的外观
有人知道如何测试 Activity 上 Toast 消息的外观吗?
我使用的代码类似于OP在 上发布的代码这个问题用于测试我的程序从一个活动到下一个活动的流程。我还希望能够测试特定活动的 Toast 消息。
Would anyone know how to test for the appearance of a Toast message on an Activity?
I'm using code similar to what the OP posted on this question for testing my program flow from one activity to the next. I'd also like to be able to test for toast messages on particular activities.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
对于那些现在在 2019 年使用 AndroidX Test API 并使用自定义 Toast 布局的用户,请尝试以下操作 (Kotlin):
For those now using the AndroidX Test API in 2019 and using a custom layout for toasts, try this (Kotlin):
那么(科特林):
What about (Kotlin):
我这样使用它:
这是一种替代方法,部分达到了目的。
I am using it like:
This is an alternate way which partially serves the purpose.
你不能——抱歉。我的意思是,无法询问 Android“嘿,Toast 正在显示吗?它是什么样子的?”。
You can't -- sorry. By which, I mean there is no way to ask Android "hey, is a Toast showing? and what does it look like?".
实际上,我们现在可以使用 robolectric 来测试 toast 消息。下面的示例是我们团队目前的做法:
希望这会有所帮助
We actually can now test for toast messages using
robolectric
. The example below is how our team is doing this for now:Hope this helps
嗯,实际上有可以测试吐司的外观。只需创建一个Toast 的子类(例如MyOwnToast)并在您的程序中使用它来代替Toast。在此子类中,您可以覆盖 show() 方法来通知您正在显示 Toast。
此外,您可以将 Toast 以 ToastDatabase 单例的形式存储在 show() 方法中,您可以在其中访问 Toast 及其在显示和销毁后的视图(尚未使用 Toast 进行测试,但我经常这样做)活动的结果意图是在它们被销毁后使它们可用于进一步的测试 - 因此使用 Toast 实现这一点应该没有问题)。
请注意:也许您必须克隆 Toast 对象或其对应的 ToastDatabase 视图,因为在 Toast 被销毁后它可能会为 null。希望这有帮助!
Hm, actually there is a possibility to test the appearance of a toast. Simply create a subclass of Toast (e.g. MyOwnToast) and use this one in your program instead of Toast. In this subclass you can overwrite the show() method to notify you, that the Toast is being shown.
Additionally you can store the Toast within the show() method in kind of a ToastDatabase singleton from where you can access the Toast and it's view also after it has been shown and destroyed (haven't tested this with Toasts, but I often do that with the result intents of activities to keep them available for further tests after they have been destroyed - so it should be no problem to implement this with Toasts).
Beware: maybe you have to clone the Toast object or it's corresponding view for the ToastDatabase because probably it will be null after the Toast has been destroyed. Hope this helps!
我检查一下,以下有效:
I check, the following works:
您可以检查是否通过消息显示了 toast
如果您使用的是自定义 toast,
You could check that the toast was shown by message
If you are using a custom toast
您可以选择 Robolectric 测试框架。要检查 toast,您可以按如下方式使用它:
you can choose Robolectric test framework.For checking toast, you can use it as below: