Reputation: 6620
I am new to Mockito, following this and am trying to find out what verify method does. It seems it is used to make sure the selected method is called once. I have the following code, and by looking at the code I can find out I am calling addBook method twice so why should I use verify? I mean in any case it is easy to make sure a method is called oncem so why should we use verify method?
String isbn = mockedBookDAL.addBook(book1);
assertNotNull(isbn);
isbn = mockedBookDAL.addBook(book1);
assertNotNull(isbn);
verify(mockedBookDAL).addBook(book1);
assertEquals(book1.getIsbn(), isbn);
Upvotes: 1
Views: 958
Reputation: 3504
imagine a class to manage an account:
public class Account {
private Logger logger;
public Account(Logger logger) {
this.logger = logger;
}
...
public void withdraw(int amount) {
...
logger.logWithdrawal(amount);
...
}
}
so to test, that the withdrawal was indeed logged, you mock the logger and verify the interaction:
public class AccountTest {
@Test
public void withdrawalShouldBeLogged() {
Logger logger = mock(Logger.class);
Account cut = new Account(logger);
int amount = 10;
cut.withdraw(amount);
verify(logger).logWithdrawal(amount);
}
}
This form of asserting is also called a spy.
A further notice: you should generally assert only one thing per test method. Verifying a spy interaction would be that assertion, so you should generally not use verify and assert in the same method.
Upvotes: 4