// Pass in a stub that was created by a mocking framework. AccessManager accessManager = new AccessManager(stubAuthenticationService); // The user shouldn't have access when the authentication service returns false. when(stubAuthenticationService.isAuthenticated(USER_ID)).thenReturn(false); assertFalse(accessManager.userHasAccess(USER_ID)); // The user should have access when the authentication service returns true. when(stubAuthenticationService.isAuthenticated(USER_ID)).thenReturn(true); assertTrue(accessManager.userHasAccess(USER_ID));
// Pass in a mock that was created by a mocking framework. AccessManager accessManager = new AccessManager(mockAuthenticationService); accessManager.userHasAccess(USER_ID); // The test should fail if accessManager.userHasAccess(USER_ID) didn't call // mockAuthenticationService.isAuthenticated(USER_ID) or if it called it more than once. verify(mockAuthenticationService).isAuthenticated(USER_ID);
// Creating the fake is fast and easy. AuthenticationService fakeAuthenticationService = new FakeAuthenticationService(); AccessManager accessManager = new AccessManager(fakeAuthenticationService); // The user shouldn't have access since the authentication service doesn't // know about the user. assertFalse(accessManager.userHasAccess(USER_ID)); // The user should have access after it's added to the authentication service. fakeAuthenticationService.addAuthenticatedUser(USER_ID); assertTrue(accessManager.userHasAccess(USER_ID));
public void deletePostsWithTag(Tag tag) { for (Post post : blogService.getAllPosts()) { if (post.getTags().contains(tag)) { blogService.deletePost(post.getId()); } } }
public class FakeBlogService implements BlogService { private final Set<Post> posts = new HashSet<Post>(); // Store posts in memory public void addPost(Post post) { posts.add(post); } public void deletePost(int id) { for (Post post : posts) { if (post.getId() == id) { posts.remove(post); return; } } throw new PostNotFoundException("No post with ID " + id); } public Set<Post> getAllPosts() { return posts; } }
public void testCreditCardIsCharged() { paymentProcessor = new PaymentProcessor(mockCreditCardServer); when(mockCreditCardServer.isServerAvailable()).thenReturn(true); when(mockCreditCardServer.beginTransaction()).thenReturn(mockTransactionManager); when(mockTransactionManager.getTransaction()).thenReturn(transaction); when(mockCreditCardServer.pay(transaction, creditCard, 500)).thenReturn(mockPayment); when(mockPayment.isOverMaxBalance()).thenReturn(false); paymentProcessor.processPayment(creditCard, Money.dollars(500)); verify(mockCreditCardServer).pay(transaction, creditCard, 500); }
public void testCreditCardIsCharged() { paymentProcessor = new PaymentProcessor(creditCardServer); paymentProcessor.processPayment(creditCard, Money.dollars(500)); assertEquals(500, creditCardServer.getMostRecentCharge(creditCard)); }