Zach Zach - 1 year ago 87
Java Question

Testing parameter values after method call in Java/Android

I have an app that connects to a peripheral over BLE. The peripheral device is set up to accept a specific command set from the device.

Here is an extremely simplified example of what happens

In the command class..

public void sendCommand(int what) {
switch(what) {
case 0:
case 1:

and in the "ble" class

public void writeToDevice(String command) {
//sets characteristic value
//and writes it

I want to be able to test that a call to sendCommand(1) results in a valid and correct command received by writeToDevice.

This seems incredibly useful in my case to make sure that all changes to the command class are still sending commands that will be correctly read by the peripheral.

There is a .NET library that does exactly what I am looking for and I am curious of a way to do this using JUnit and/or any other testing libraries for Android.

I am currently trying out Mockito but would be open to any libraries that I would be able to do this with.

Answer Source

You can do this easily in Mockito, provided you can replace the ble field. I've done so below with a constructor argument, but you could do so with a setter or a field just as well. You might also choose to have a limited-visibility constructor/setter/field so you can replace dependencies in tests but use hard-coded default dependencies in production. (Note that in situations with static or final method calls, like for Android library classes or unchangeable static libraries, you would need to write a wrapper class or use more-invasive testing libraries; PowerMock and Robolectric come to mind.)

Your test would look roughly like this:

// Create a Mockito mock, which is an automatic subclass with
// all of its methods overridden to track and verify every method call.
BleService mockBleService = Mockito.mock(BleService.class);

// Importantly, you need to make sure that your system under test calls this
// new object instead of the default (real) dependency.
Command commandUnderTest = new Command(mockBleService);

// Now you interact with your Command exactly like you'd expect consumers to.

// Using the static method Mockito.verify, you can confirm the call came through.

Once you're familiar with that, read up the Mockito documentation, particularly top-level sections 1 (verification), 2 (stubbing), and 9 (@Mock annotations).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download