Description: Trying to mock this class (from some library):
public class Signal{
public static Signal fromPool(){
// returns a recycled instance from a signal pool
}
public int getCode(){
// returns some signal code;
}
}
Class Sender
uses Signal.fromPool()
internally :
public class Sender{
private Signal sig;
public void ready(){
sig = Signal.fromPool();
System.out.println(sig);
}
public void send(OutputStream output){
output.write(sig.getCode());
}
}
And we need to write some unit tests for Sender
.
But, In Unit test environment, Signal.fromPool()
will fail, because environment lacks some internal dependencies.
Hence, we decide to use "JMockit" to mock Signal
class:
public class SenderTest{
// mock signal class
static class MockSignal extends Mockup<Signal>{
@Mock
public static Signal fromPool(){
return new Signal();
}
@Mock
public int getCode(){
return 42;
}
}
@Test
public void testSending(@Mocked OutputStream stream){
// replace Signal with MockSignal
new MockSignal();
// should write 42
new Expectations(){{
stream.write(42);
}};
// test code
Sender sender = new Sender();
sender.ready();
sender.send(stream);
}
}
Problem: Mocked Signal.fromPool
returns a null
. This statement in above code prints null
:
System.out.println(sig);
My understanding is that perhaps inside the mocked fromPool
the Mocked class itself isn't being instantiated:
@Mock
public static Signal fromPool(){
return new Signal();
}
How can new Signal
return null
? Anyone has a better perspective ?