简体   繁体   中英

How to unit test a View class

I want to write some unit tests for a custom view class. The class extends EditText. Its constructor takes a context and and AttributeSet as required arguments.

class CustomEditText(context: Context, attrs: AttributeSet) : AppCompatEditText(context, attrs) {
...
}

Since I need a Context, I gave up on making a unit test, and instead tried to make an instrumented test so that I could get access to ApplicationProvider.getApplicationContext(). However, I still need an AttributeSet. AttributeSet is an interface. It's not clear to me which classes implement this interface, or how I'll need to initialize it so that I can get an instance of the view class.

How can I create an isolated instance of this class so I can test it?

How can I create an isolated instance of this class so I can test it?

Either use a single-arg constructor that just takes a Context or use LayoutInflater.from(context) then inflate(...) to load your view from a test XML file (which would create the AttributeSet for you).

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM