TeodorKolev TeodorKolev - 9 months ago 51
Android Question

Unable to find Textview in testing

I am unable to find Textview by id in test. What I do wrong?

private MyActivity myActivity;
public void setUp() throws Exception {
myActivity= Mockito.mock(MyActivity .class);


public void testFindView() throws Exception {
System.out.println(myActivity); // This is not null
TextView viewText = (TextView) this.myActivity.findViewById(R.id.container_text);
System.out.println(viewText ); // This is null


Calling Mockito.mock() doesn't create a real instance, but only an artificial one. It's main purpose is to keep unit tests away from any external dependencies and track interactions with an object.

So when you call this.myActivity.setContentView(R.layout.container); nothing really happens, because mocked myActivity doesn't have the insides of a regular MyActivity - you're only calling a stub method that you have not ordered to do anything. So you need to create a real instance of MyActivity if you want to test how it works. You can also play with Spy objects if you still want to track interactions (you can check them out here)