Mockito NullPointerException创建Repository的对象时

时间:2018-03-24 13:45:53

标签: android mockito

public class DriveInteractor implements DriveContract.Interactor {

    private final DriveRepository driveRepository;

    public DriveInteractor(Context context) {
        DriveApplication application = (DriveApplication) context.getApplicationContext();
        this.driveRepository = application.getDriveRepository();
    }

    @Override
    public List<Drive> getDrive() {

        List<Drive> drives = driveRepository.getDrives();

        return drives;
    }
}

以下是我使用的测试类的代码 Mockito

@RunWith(PowerMockRunner.class)
public class DriveInteractorTest {

    @Mock
    private Context context;
    @Mock
    private  DriveRepository driveRepository;
    @Mock
    private List<Drive> driveList;

    @Mock
    private DriveApplication driveApplication;

    private DriveInteractor driveInteractor;

    @Before
    public void setUpDriveInterator(){
    MockitoAnnotations.initMocks(this);
    driveInteractor = new DriveInteractor(context);
}
.....}

我还在我的测试类中编写了一个测试方法。一旦我运行我的测试方法,我就会一直指向空指针异常指向DriveRepository

我甚至尝试在setUpDriveInterator方法中创建Drive POJO类的对象并添加到arraylist,但它不起作用:

public class DriveRepository {

    private List<Drive> drives;

    public DriveRepository(Context context) {
        drives = new ArrayList<>();
        drives.add(Drive.create(context, "ABC", "Honda"));
.....
       }
....}

需要在DriveInterator中传递哪些上下文进行测试?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

存根你的context.getApplicationContext();测试方法中的一段代码。

类似下面的Mockito.when(context.getApplicationContext()).thenReturn(driveApplication);

希望它有用。