IntoTheDeep
IntoTheDeep

Reputation: 4118

Unable to find Textview in testing

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

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

Test:

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

Upvotes: 0

Views: 84

Answers (1)

Shem
Shem

Reputation: 565

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)

Upvotes: 1

Related Questions