Reputation: 6516
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]")))
.
Upvotes: 4
Views: 1889
Reputation: 2939
You can use anyString() method as given below
Mockito.when(mockedObject.someMethod(Mockito.anyString())).thenReturn(object1);
Mockito.when(mockedObject.someMethod(Mockito.eq("anotherString"))).thenReturn(object2);
Upvotes: 0
Reputation: 7937
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.
Upvotes: 3