Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito - how to mock different behaviors for different arguments

I want a simple mock to behave one way when called with a given argument, and another when called with everything else.

I've tried variations on this:

when(this.mockWebElement.findElement(not(eq(By.xpath("./td[1]"))))).thenReturn(this.mockWebElement);
when(this.mockWebElement.getText()).thenReturn("someString");

when(this.mockWebElement.findElement(By.xpath("./td[1]"))).thenReturn(dateMockElement);
when(dateMockElement.getText()).thenReturn("8/1/2014", "7/1/2014", "6/1/2014", "5/1/2014");

The call to getText(By.xpath("./td[1]")) always returns "someString". I've also tried and(eq(any(By.class)), not(eq(By.xpath("./td[1]"))).

like image 504
jordanpg Avatar asked Oct 14 '25 12:10

jordanpg


1 Answers

Using your code as a basis, the following test passed for me:

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

    @Mock private WebElement mockWebElement;
    @Mock private WebElement dateMockElement;

    @Test
    public void testX() throws Exception {
        when(this.mockWebElement.findElement(not(eq(By.xpath("./td[1]"))))).thenReturn(this.mockWebElement);
        when(this.mockWebElement.getText()).thenReturn("someString");

        when(this.mockWebElement.findElement(By.xpath("./td[1]"))).thenReturn(dateMockElement);
        when(dateMockElement.getText()).thenReturn("8/1/2014", "7/1/2014", "6/1/2014", "5/1/2014");

        WebElement w = mockWebElement.findElement(By.xpath("./td[1]"));
        String x= w.getText();
        assertEquals("8/1/2014", x);
    }

Since you haven't shown the rest of the test, I'm assuming the error is in the rest of your plumbing of the actual test setup and execution.

like image 117
Kevin Welker Avatar answered Oct 17 '25 01:10

Kevin Welker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!