Skip to content

Instantly share code, notes, and snippets.

@kennycason
Created December 16, 2013 23:45
Show Gist options
  • Save kennycason/7997208 to your computer and use it in GitHub Desktop.
Save kennycason/7997208 to your computer and use it in GitHub Desktop.
Mockito example
package app.datasources.amazon;
import app.hmodels.entities.ItemEntity;
import app.hmodels.repositories.ItemRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.net.URL;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
/**
* Created by kenny on 12/16/13.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles({"local"})
public class STestAmazonProductUrlHandler {
@Configuration
@ComponentScan(basePackages = "app.configuration")
public static class OverrideConfiguration {
@Bean
@Primary
public ItemRepository getItemRepository() {
return Mockito.mock(ItemRepository.class);
}
}
@Autowired
private ItemRepository itemRepository;
@Autowired
AmazonProductUrlHandler amazonProductUrlHandler;
@Captor
ArgumentCaptor<ItemEntity> captor;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void handleTest() throws Exception {
URL url = new URL("http://www.amazon.com/s?field-keywords=Tide+Pods&page=1");
this.amazonProductUrlHandler.setItemRepository(this.itemRepository);
this.amazonProductUrlHandler.handle(url);
Mockito.verify(this.itemRepository, atLeastOnce()).put(captor.capture());
List<ItemEntity> itemEntities = captor.getAllValues();
for(ItemEntity itemEntity : itemEntities) {
System.out.println(itemEntity);
assertNotNull(itemEntity);
assertNotNull(itemEntity.getId());
assertTrue(itemEntity.getId().startsWith("A_B"));
assertTrue(itemEntity.getItemId().startsWith("B"));
assertNotNull(itemEntity.getName());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment