The real object is used because I assume that you have the ObjectGraph initialization in your Application class. When you call ((Application) getApplication()).inject(this) during the tests, you use the same ObjectGraph as when starting your application.
In this test, you create a completely new ObjectGraph with a mock instance of MyObject . This layout is only entered in MainActivityTest because when it is MainActivity in MainActivity inject() , it uses the ObjectGraph made in Application .
What you can do is make the TestApplication class (it must have the same package as your Application class, but must be in the test directory) whitch extends your application and adds your TestModule to override the real instances with mocks. For example, as follows:
Myapplication.java
package com.example.myapp; public class MyApplication extends Application { ObjectGraph graph; private Account currentAccount; @Override public void onCreate() { super.onCreate(); graph = ObjectGraph.create(getModules().toArray()); init(); } void init() {
TestMyApplication.java
package com.example.myapp; public class TestMyApplication extends MyApplication { @Override void init() { } @Override List<Object> getModules() { modules = super.getModules(); modules.add(new TestModule()); return modules; } }
source share