25
loading...
This website collects cookies to deliver better user experience
public class IncrementNumber {
public int getIncrementedNumber(int num){
DBConn conn = getConn();
return conn.getValue(num);
}
DBConn getConn(){
return DBConnFactory.establishConnection();
}
}
getIncrementedNumber
method in this class but we can see how it's dependent on Database Connection to return the output. We can't establish the connection in test class and make it call the actual Database just to test the behaviour of the method, right? So, How do we mock the behaviour?getConn
to return my own mock for DBConn. That looks like this :public class MockIncrementNumber extends IncrementNumber{
MockDBConn conn;
@Override
DBConn getConn(){
this.conn = new MockDBConn();
return this.conn;
}
}
getValue
and return the output, so that needs to be overridden as well. This is how it looks :public class MockDBConn extends DBConn{
@Override
public int getValue(int param){
return param + 4;
}
}
@Test
public void shouldReturnIncrementedValue{
IncrementNumber inc = new MockIncrementNumber();
assert inc.getIncrementedNumber(4) == 8;
}