Unit Tests and Mocking
Christopher Parnin
JUnit
•A Java framework for writing and running unit tests
•Test cases and fixtures
•Test suites
•Test runner
•Written by Kent Beck and Erich Gamma
•Written with “test first” and pattern-based development in mind
•Tests written before code
•Allows for regression testing
•Facilitates refactoring
Working Example: Testing MyList
•Unit to be tested
• MyList
•Methods under test
•add()
•remove()
•contains()
•size()
•Concrete Test case
• MyListTestCase
JUnit Classes
Test Cases
Fixtures and Test Cases
Behavior-Driven Development - BDD
Narrative
Business need and user
Acceptance scenarios
Initial condition
Trigger (when)
Outcome
Behavior-Driven Development - BDD
Story: Returns go to stock��In order to keep track of stock�As a store owner�I want to add items back to stock when they're returned��Scenario 1: Refunded items should be returned to stock�Given a customer previously bought a black sweater from me�And I currently have three black sweaters left in stock�When he returns the sweater for a refund�Then I should have four black sweaters in stock
Tools such as Cucumber run as unit tests.
TDD is dead. Long live testing.
Mockito
Simple example
List<Status> statuses = new ArrayList<Status>()
testStatus = Mockito.mock(Status.class);
when(testStatus.getId()).thenReturn(900000L);
when(testStatus.getRetweetCount()).thenReturn(33);
statuses.add(testStatus);
Status bestTweet = best.mostRetweeted(statuses); assertEquals(bestTweet.getId(), 900000L );
assertEquals(bestTweet.getRetweetCount(), 33 );
Principles
http://stackoverflow.com/questions/1906344/should-you-only-mock-types-you-own
http://martinfowler.com/articles/mocksArentStubs.html
Selenium
Selenium automates browsers. That's it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.
JUnit + Selenium
private WebDriver driver;
@Before
public void setUp() throws Exception
{
driver = new HtmlUnitDriver();
}
@Test
public void googleExists() throws Exception
{
this.driver.get("http://www.google.com");
assertEquals("Google", this.driver.getTitle());
}
More complex: Ensure #1 result
this.driver.get("http://www.google.com");
WebElement search = this.driver.findElement(By.name("q"));
search.sendKeys("ncsu iTrust");
search.sendKeys(Keys.RETURN);
WebDriverWait wait = new WebDriverWait(this.driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("resultStats")));
List<WebElement> links = this.driver.findElements(By.xpath("//a[@data-href]"));
int rank = 0;
for( WebElement link : links )
{
if( link.getAttribute("data-href").equals("http://agile.csc.ncsu.edu/iTrust/wiki/"))
{
break;
}
rank++;
}
assertEquals(0, rank);
HW1.P2