1

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)

Cruces
  • 3,029
  • 1
  • 26
  • 55

1 Answers1

0

What your code is doing is called Dependency_injection

Is there a better way to do this?

There is not one "better" way to do it but there are different ways to do it that depend on the tools you are using (see why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code for details.)

I would have implemented it the same way you have done it because your code can be used without any di containers so it is has less external dependencies.

k3b
  • 14,517
  • 7
  • 53
  • 85
  • yeah I know about dependency injection, I was actually thinking of using an interface like `interface IAdapterProvider { val adapter: IBluetoothAdapter}` having a default value passed on through the constructor and in my tests passing something like `object TestAdapterProvider : IAdapterProvider { override val adapter get() = mock(IBluetoothAdapter::class.java) }` I was just wandering if there is a way to use a specific implementation when running unit tests and on live code, sort of like different flavours – Cruces Jul 02 '19 at 18:03