代码之家  ›  专栏  ›  技术社区  ›  user8412632

创建存储库对象时的Mockito NullPointerException

  •  1
  • user8412632  · 技术社区  · 8 年前
    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;
        }
    }
    

    下面是我正在使用的测试类的代码 莫基托 :

    @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

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

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

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   Praveen Kumar Mekala    8 年前

    存根上下文。getApplicationContext();测试方法中的一段代码。

    如下所示 Mockito.when(context.getApplicationContext()).thenReturn(driveApplication);

    希望有用。