nuicca
nuicca

Reputation: 778

Android context not getting mocked when testing

I have problems testing SubClass in this kind of structure, where i have to deliver Activity's Context down into a FileUsageTool-class, where i write and read data about state of SubClass and SuperClass.

public class FragmentA extends Fragment {
    SubClass = new SubClass(getActivity()); //Context from getActivity()
}

public class SubClass extends SuperClass {
   public SubClass(Context ctx) {
      super(ctx);
      line = "hello world";

      //file doesn't exist yet even thought we have created File object in 
      //FileUsageTools constructor
      if (!filer.file.exists()) {

         filer.saveFile(this);
      }
   }
}

public class SuperClass {
    String line;
    public SuperClass(Context ctx) {
       FileUsageTool filer = new FileUsageTool(ctx);
    }
}

And here in class FileUsageTool I have to use context to create a file and to write to it. saveToFile will be called in both, SuperClass and SubClass.

public class FileUsageTool {
   Context context;
   File file;

   FileUsageTool(Context ctx) {
       context = ctx;
       file = new File(ctx.getFilesDir(), "asd.txt");
   }

   saveFile(SuperClass spr) {
        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        writer.println(spr.line);
        writer.close();
   }
   }

But when i want to test the SubClass and mock Context and FileUsageTool classes

@RunWith(MockitoJUnitRunner.class)
public class SubClassTest {

   @Mock
   private Context mockContext;
   @Mock
   private FileUsageTool mockFileUsageTool;
   @InjectMocks
   private SubClass subClass = new SubClass(mockContext);

   public testCase() {
      assertEquals(subClass.line == "hello world");
   }

I keep getting NullPointerException at if (!filer.file.exists()) when i run the test even if I take the mockFileUsageTool off. The problem might be in mocking or something else.

Upvotes: 0

Views: 760

Answers (1)

Hamady C.
Hamady C.

Reputation: 1225

I believe it is because you use the context in the initialization.

try this

  @RunWith(MockitoJUnitRunner.class)              public class SubClassTest { 
  @Mock private Context mockContext;                  @Mock private FileUsageTool  mockFileUsageTool; 

@InjectMocks private SubClass subClass;

  @override
  protected void setUp() {
     subClass = new SubClass(mockContext)
 }

  public testCase() { 
    assertEquals(subClass.line == "hello world"); 

}

Upvotes: 1

Related Questions