I’m trying to write unit tests for an I2C device, my mentor is saying that I need to create a dummy I2C device. How would I do this? I found i2c-stub for C, but not one for java.
Because I2C is already pretty low level, you will probably end up creating an interface that abstracts communicating with an I2C device. What will most likely happen is that you create two classes that implement that interface. One of those classes will have an I2C device and the other will be the one you unit test with.
I can’t tell you the best way to set it up because there isn’t a best way, and I don’t have enough information on what I2C device you’re using and what class you’re using for it, etc.
Thanks. The issue I’m running into now is it’s not using the dummy method I created (shown here: https://gist.github.com/Dev-Osmium/71109ce6afada076169acce8d11e1567)
Can you post the code that is calling that? Also, because of how low level I2C is, you shouldn’t reference that class directly if you really want to unit test it, you shouldn’t inherit it. Because I2C is its own class that does its own thing that’s part of WPILib, it’s pretty much guaranteed to work. You shouldn’t try to unit test something in WPILib, let the devs handle that.
I would recommend creating an interface like this:
interface DeviceToCommunicateWith {
String readMessage();
void sendMessage(String string);
}
class DeviceToCommunicateWith1234 implements DeviceToCommunicateWith {
String readMessage(){
return this.i2c.read...
}
void sendMessage(String string){
this.i2c.write...
}
}
class TestDeviceToCommunicateWith implements DeviceToCommunicateWith {
String readMessage(){
return dummyMessage;
}
void sendMessage(String string){
// do something with string
}
}
I added the file to the gist