开发者

I am trying to unit test a custom Dialog in Android and I can't seem to instantiate it

I am unit testing an application that includes a custom dialog. This dialog inherits from android.app.Dialog but requires a speciall subclass of Activity, let's call it CustomActivity, that provides some functions it needs.

I want to avoid instantiating one of the Activities from the tested application since I already have tests for them. I'm unit testing, not black-box-testing, so I want to run all the public functions in the dialog. This is not possible, however, without instantiating the dialog first and that requires a CustomActivity instance.

I've tried to create a mock subclass of CustomActivity and use that to launch the dialog, but I keep running into the same problem: The test application is not looking for activities in the test-application, only in the tested application. So I get "Unable to resolve activity".

I've also tried to create the activity myself, without using Instrumentation.launchActivity but that requires a context, which I don't have under InstrumentationTestCase. If I use AndroidTestCase instead, the provided context (via getContext) is just a ContextWrapper which doesn't seem to wrap any context, so I'm back to square one. I need to instantiate the activity first.

I've googled quite a bit and I can't believe I am the first person ever to need to unit test a Dialog. It seems to me that I would need something similar to the ActivitiTestCase2 but for dialogs that provide the necessary context.

What is the best way to create my d开发者_运维知识库ialog? Is there another way I haven't tried? Does anyone have an example of a custom dialog unit-test?


This sounds like an object-oriented problem rather than an Android problem. I think your core problem may be your tight coupling between the classes. Try introducing an interface in front of CustomActivity that exposes only the functions that your dialog needs, then mock the interface in your tests, instead of trying to create a mock subclass of the activity itself. Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜