mardi 2 juillet 2019

Using different classes for testing and normal runs in android

I'm trying to build an library that helps my application communicate with other devices using bluetooth

In order to achieve this I created an interface like so:

 interface IBluetoothAdapter {
     ....
 }

On normal runs I use it like so:

 internal class BTAdapter : IBluetoothAdapter {
      private val mAdapter = BluetoothAdapter.getDefaultAdapter()
 }

and I use it to send messages to the actual bluetooth adapter

when I run my tests I mock IBluetoothAdapter and this works decently

in order to facilitate the above my actual class has this implementation:

class Communicator(val address:String) {
     private var mAdapter: IBluetoothAdapter = BTAdapter()

     @VisibleForTesting
     @TestOnly
     fun setAdapter(adapter: IBluetoothAdapter) {
         mAdapter = adapter
     }

     .....
}

Is there a better way to do this?

Basically what I want to do is when the application runs in tests to always use one specific class (the mock) and when it runs normally to always use another (the one I created)

Aucun commentaire:

Enregistrer un commentaire