jeudi 30 mars 2017

Mockito when() on method of field

I'm trying to test with Mockito the interactor in simple application, that works as Finite state machine.

public class Machine {

private OnActionListener mListener;
private ArrayList<State> mStates;
private FSMJsonParser parser;

private State mCurrentState;

public Machine(String jsonConfig, OnActionListener listener, FSMJsonParser parser) throws IOException {

    this.mListener = listener;
    this.parser = parser;
    initStates(jsonConfig);
    mCurrentState = getStateByName("AlarmArmed_AllLocked");
}

private void initStates(String jsonConfig) throws IOException{

    mStates = parser.parseFSMFromJson(jsonConfig);
}

There is test:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FSMJsonParser.class)
public class FSMtest {

@Mock
State state;

@Mock
ControlPresenter presenter;

@Mock
FSMJsonParser parser;

@InjectMocks
Machine machine;

@Before
public void setUp() throws IOException {

    when(parser.parseFSMFromJson(anyString())).thenReturn(parseFSMFromJson(readConfig()));
}

@Test
public void testAlarmArmedAllLockedStateActions() throws IOException{

    machine.lock();
    verify(machine, times(1)).setCurrentState(anyString());

    machine.lockx2();
    verify(machine, times(1)).setCurrentState("AlarmArmed_AllLocked");

    machine.unlock();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_DriverUnlocked");

    machine.unlockx2();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_AllUnocked");
}

I provide a parse JSON (with states description, stored in assets) with method parseFSMFromJson(readConfig()). When ran test with debug mode, JSON was parsed properly. But fields of Machine mock object didn't initialized, and was null and all tests failed. I need to initialize ArrayList mStates for correct work of Machine class. How to test this class properly??

Aucun commentaire:

Enregistrer un commentaire