How to mock static methods with more than one argument

Singh :

I'm writing a test case to test a component that invokes a static method accepting 5 arguments. I want to know how I can do that.

Earlier I have been successful in mocking static method with 0 and 1 arguments. However when I mock a static method with more than 1 argument, it returns null. Following is a simplified version of what I'm trying to do. The static method has 2 arguments.

public interface VO {

}
public class A implements VO {
    private int value = 5;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}
public class Factory {
    public static VO getObj(String a, String b) {
        return new A();
    }
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({com.csc.fsg.nba.vo.Factory.class})
public class APITest {


    @BeforeClass
    public static void runOnceBeforeClass() throws Exception {
        System.out.println("Executing runOnceBeforeClass()");
        A a = new A();
        a.setValue(3);
        PowerMockito.mockStatic(Factory.class);
        Mockito.when(Factory.getObj(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(a);
    }

    @Test
    public void testA() throws Exception {
        VO vo = Factory.getObj("a", null);
        System.out.println(((A)vo).getValue());
    }

}

I'm expecting that sysout should print 3, however vo is null.

Nkosi :

In this particular case the any(String.class) fails to match the null passed when exercising the test

//...

VO vo = Factory.getObj("a", null);

//...

Use anyString()

//...

when(Factory.getObj(anyString(), anyString())).thenReturn(a);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307969&siteId=1