Siva
Siva

Reputation: 1940

Mocking a method which takes String as a parameter Mockito

I am trying to mock a method which takes String as a parameter, Based on the string value i wanted to return different values, below is my Sample code

when(mockVariableResolver.resolveVariable(
    (FacesContext)anyObject(),      
     Mockito.eq(ProgramConstants.SRCH_PROC_DATA_BEAN))).
thenReturn(searchProcedureCodeDataBean);

The resolveVariable metjos takes an object and a string, Object might be anything but the second argument must match, The above one did not worked.

EDIT:

Signature for resolveVariable metod is

fc.getApplication().getVariableResolver().resolveVariable(fc,
                                        "#{" + ProgramConstants.SRCH_PROC_DATA_BEAN + "}")

Please help me on this.

Upvotes: 1

Views: 5872

Answers (2)

sina72
sina72

Reputation: 5101

Based on your description, I would implement it as Mockito.Answer:

when(mock.resolveVariable(anyObject(), anyString())).thenAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        String secondArgument = (String) args[1];
        //
        // TODO: make return value depend from secondArgument
        return null;
    }
});

Upvotes: 4

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

I'm guessing here but perhaps

when( mockVariableResolver )
    .resolveVariable( (FacesContext)anyObject(),      
                      Mockito.eq( ProgramConstants.SRCH_PROC_DATA_BEAN ) ) )
    .thenReturn( searchProcedureCodeDataBean );

will do the trick.

Note that the resolveVariable() method is moved outside the when() argument list, which should always be just a @Mock.

Cheers,

Upvotes: 0

Related Questions