简体   繁体   中英

how Unit test methods of Kotlin class with private constructor, companion object and extending another class without mocking

My class is extending another class and has companion object and private constructor. I have to Unit test getLastKnownLocation() method. I dont want mock GpsTrackingService class and would like instantiate it in my test class. How I can do it? Thanks for any help, in advance

 class GpsTrackingService private constructor(private val context: Context, private val Snavigator: SNavigator?) : LocationListener {
    
        companion object {}
    
    getLastKnowLocation() {}
    }

You can make the constructor internal , mock the dependencies, and use them to instantiate your class.

class GpsTrackingServiceTest {
   
   private lateinit var context: Context
   private lateinit var sNavigator: SNavigator
   private lateinit var trackingService: GpsTrackingService

   @Before
   fun setup() {
      context = Mockito.mock(Context::class.java)
      sNavigator = Mockito.mock(SNavigator::class.java)
      trackingService = GpsTrackingService(context, sNavigator)
   }

   @Test
   fun test_getLastKnowLocation() {
      trackingService.getLastKnowLocation()
      // do your verifications, etc
   }
}

This worked for me

class GpsTrackingServiceTest {
   
   private lateinit var mContext: Context
   private lateinit var sNavigator: SNavigator
   private lateinit var trackingService: GpsTrackingService

   @Before
   fun setup() {
      cmContext = InstrumentationRegistry.getInstrumentation().context
      sNavigator = Mockito.mock(SNavigator::class.java)
      trackingService = GpsTrackingService.getInstance(mContext, redNavigator)
   }

   @Test
   fun test_getLastKnowLocation() {
      trackingService.getLastKnowLocation()
      // do your verifications, etc
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM