L08	
  Unit	
  Testing
Reading
▪ Optional	
  
– http://www.junit.org	
  
– JUnit	
  Test	
  Infected:	
  

Programmers	
  Love	
  Writing	
  Tests
▪ Extreame	
  Programming	
  Philosophy:	
  
– “Build	
  a	
  little,	
  test	
  a	
  little”	
  
▪ All	
  classes	
  have	
  unit	
  testing	
  classes	
  
– Run	
  on	
  regular	
  basis	
  
▪ Unit	
  test	
  
– A	
  structured	
  set	
  of	
  tests	
  that	
  exercises	
  the	
  methods	
  of	
  
a	
  class	
  
▪ Test	
  Driven	
  Development	
  –	
  TDD	
  
Background
▪ Is	
  this	
  your	
  code?	
  Big	
  ball	
  of	
  Mud
Background
▪ Why	
  is	
  unit	
  testing	
  a	
  good	
  idea?	
  
▪ Reasons:	
  
– Gives	
  the	
  developer	
  confidence	
  that	
  the	
  class	
  is	
  
working	
  properly	
  
– Quickly	
  finds	
  the	
  source	
  of	
  bugs	
  
– Focuses	
  the	
  developer	
  on	
  the	
  design	
  of	
  a	
  class	
  
– Helps	
  define	
  the	
  requirements	
  of	
  the	
  individual	
  
classes
Why Unit Testing
▪ Why	
  is	
  unit	
  testing	
  a	
  good	
  idea?	
  
▪ And	
  the	
  really	
  good	
  reason:	
  
– In	
  large	
  application,	
  changes	
  and	
  re-­‐factoring	
  are	
  
possible
Why Unit Testing
1. Build	
  a	
  unit	
  test	
  to	
  test	
  a	
  class	
  during	
  design	
  
This	
  will	
  test	
  the	
  design	
  
Focuses	
  the	
  developer	
  on	
  the	
  design	
  of	
  a	
  class	
  
2. Stub	
  out	
  the	
  class	
  
All	
  tests	
  will	
  fail	
  since	
  there	
  is	
  no	
  code!	
  
3. Write	
  the	
  functionality	
  in	
  the	
  class	
  
Until	
  the	
  test	
  will	
  pass
Building the Tests
▪ An	
  open	
  source	
  Java	
  unit	
  testing	
  tool	
  
– Developed	
  by	
  Erich	
  Gamma	
  and	
  Kent	
  Beck	
  
▪ Location:	
  	
  
– www.junit.org	
  	
  
▪ JUnit	
  tests	
  does	
  not:	
  
– Take	
  the	
  place	
  of	
  functional	
  testing	
  
– Separate	
  data	
  from	
  test	
  code	
  (look	
  at	
  JUnit++)	
  
– Can’t	
  unit	
  test	
  Swing	
  GUIs,	
  JSPs	
  	
  or	
  HTML	
  (look	
  at	
  JUnit	
  
extensions)
JUnit
▪ Java	
  based	
  testing	
  framework	
  to	
  make	
  writing	
  and	
  
maintaining	
  unit	
  tests	
  easier	
  
▪ Uses	
  testcases	
  and	
  testsuits	
  to	
  build	
  a	
  	
  hierarchy	
  of	
  
tests	
  which	
  can	
  be	
  run	
  to	
  test	
  the	
  whole	
  system	
  or	
  
individual	
  modules/classes	
  
▪ The	
  developer	
  creates	
  the	
  unit	
  tests	
  using	
  JUnit	
  
utilities,	
  extends	
  JUnit	
  test	
  classes	
  and	
  uses	
  a	
  test	
  
runner	
  to	
  run	
  them
What is JUnit?
package test;
import junit.framework.TestCase;
import junit.framework.Assert;
import domain.Money;
public class MoneyTestCase extends TestCase {
private Money f12CHF;
private Money f14CHF;
protected void setUp () {
f12CHF = new Money(12, "CHF");
f14CHF = new Money(14, "CHF");
}
public void testSimpleAdd() {
Money expected = new Money(26,"CHF");
Money results = f12CHF.add(f14CHF);
Assert.assertTrue(expected.equals(results));
}
Test Case
public void testEquals ()
{
Assert.assertTrue(!f12CHF.equals(null));
Assert.assertEquals(f12CHF, f12CHF);
Assert.assertEquals(f12CHF, new Money (12, "CHF"));
Assert.assertTrue(!f12CHF.equals(f14CHF));
}
}
Test Case
@Test
public void multiplicationOfZeroIntegersShouldReturnZero() {
// MyClass is tested
MyClass tester = new MyClass();
// Tests
assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0));
assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10));
assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));
}
Annotations
package test;
import junit.framework.TestSuite;
public class TestRunner
{
public static void main(String[] args)
{
// the testcase
String[] testCaseName = { MoneyTestCase.class.getName()};
// testrunner
junit.swingui.TestRunner.main(testCaseName);
//junit.textui.TestRunner.main(testCaseName);
}
}
Test Case Runner
junit.textui.TestRunner.main(testCaseName);
junit.swingui.TestRunner.main(testCaseName);
Running the Tests
public class TestContent extends TestCase
{
ContentServicecontentService;
protected void setUp() throws Exception
{
contentService = new ContentService();
contentService.setMailGateway(new MailServerStub());
contentService.setContentDataGateway(new ContentDataGatewayStub());
}
public void testService() throws ServiceException
{
contentService.addContent(new Content(1, "Video 1", "http", "", new D
List<Content> list = contentService.getContents();
assertEquals(list.size(), 1);
}
Example
Player Example
▪ Spring	
  Test	
  Framework	
  
▪ JUnit	
  
▪ PlayerService
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
Player Example
pom.xml
package is.ru.honn.rufan.domain;



public class Player

{

protected int playerId;

protected String username;
protected String name;



public Player()

{

}



public Player(int playerId, String username, String name)

{

this.playerId = playerId;

this.username = username;

this.name = name;

}

...
Player Example
package is.ru.honn.rufan.service;



import is.ru.honn.rufan.domain.Player;



public interface PlayerService

{

public int addPlayer(Player player) throws ServiceException;

public Player getPlayer(int playerId);

}

Player Example
package is.ru.honn.rufan.service;



import is.ru.honn.rufan.domain.Player;

import java.util.ArrayList;

import java.util.List;

import java.util.logging.Logger;



public class PlayerServiceStub implements PlayerService

{

Logger log = Logger.getLogger(PlayerServiceStub.class.getName());

private List<Player> players = new ArrayList<Player>();



Player Example
public int addPlayer(Player player) throws ServiceException

{

for(Player p: players)

{

if (p.getUsername() == player.getUsername())

{

String msg = "Username: '" + player.getUsername() + 

"' already exists.";

log.info(msg);

throw new ServiceException(msg);

}

}



players.add(player);

return players.size()-1;

}



Player Example


public Player getPlayer(int playerId)

{

for(Player p: players)

{

if (p.getPlayerId() == playerId)

return p;

}



return null;

}



}

Player Example
Demo
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
beans/spring-beans.xsd">
<bean id="service"
class="is.ru.honn.rufan.service.PlayerServiceStub" />
</beans>
Player Example
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:app-test-stub.xml")
public class testPlayerService extends TestCase
{
Logger log = Logger.getLogger(testPlayerService.class.getName());
@Autowired
private PlayerService service;
@Before
public void setUp()
{
}
Player Example
@Test
public void testUser()
{
Player player0 = new Player(0, "messi", "Messi");
Player player1 = new Player(1, "ronaldo", "Ronaldo");
service.addPlayer(player0);
service.addPlayer(player1);
// Test if add works
Player playerNew = service.getPlayer(1);
assertSame(playerNew, player1);
Player Example
// Test if same username fails
try
{
service.addPlayer(player1);
}
catch (ServiceException s)
{
assertSame(ServiceException.class, s.getClass());
}
}
}
Player Example

L08 Unit Testing

  • 1.
  • 2.
    Reading ▪ Optional   –http://www.junit.org   – JUnit  Test  Infected:  
 Programmers  Love  Writing  Tests
  • 3.
    ▪ Extreame  Programming  Philosophy:   – “Build  a  little,  test  a  little”   ▪ All  classes  have  unit  testing  classes   – Run  on  regular  basis   ▪ Unit  test   – A  structured  set  of  tests  that  exercises  the  methods  of   a  class   ▪ Test  Driven  Development  –  TDD   Background
  • 4.
    ▪ Is  this  your  code?  Big  ball  of  Mud Background
  • 5.
    ▪ Why  is  unit  testing  a  good  idea?   ▪ Reasons:   – Gives  the  developer  confidence  that  the  class  is   working  properly   – Quickly  finds  the  source  of  bugs   – Focuses  the  developer  on  the  design  of  a  class   – Helps  define  the  requirements  of  the  individual   classes Why Unit Testing
  • 6.
    ▪ Why  is  unit  testing  a  good  idea?   ▪ And  the  really  good  reason:   – In  large  application,  changes  and  re-­‐factoring  are   possible Why Unit Testing
  • 7.
    1. Build  a  unit  test  to  test  a  class  during  design   This  will  test  the  design   Focuses  the  developer  on  the  design  of  a  class   2. Stub  out  the  class   All  tests  will  fail  since  there  is  no  code!   3. Write  the  functionality  in  the  class   Until  the  test  will  pass Building the Tests
  • 8.
    ▪ An  open  source  Java  unit  testing  tool   – Developed  by  Erich  Gamma  and  Kent  Beck   ▪ Location:     – www.junit.org     ▪ JUnit  tests  does  not:   – Take  the  place  of  functional  testing   – Separate  data  from  test  code  (look  at  JUnit++)   – Can’t  unit  test  Swing  GUIs,  JSPs    or  HTML  (look  at  JUnit   extensions) JUnit
  • 9.
    ▪ Java  based  testing  framework  to  make  writing  and   maintaining  unit  tests  easier   ▪ Uses  testcases  and  testsuits  to  build  a    hierarchy  of   tests  which  can  be  run  to  test  the  whole  system  or   individual  modules/classes   ▪ The  developer  creates  the  unit  tests  using  JUnit   utilities,  extends  JUnit  test  classes  and  uses  a  test   runner  to  run  them What is JUnit?
  • 10.
    package test; import junit.framework.TestCase; importjunit.framework.Assert; import domain.Money; public class MoneyTestCase extends TestCase { private Money f12CHF; private Money f14CHF; protected void setUp () { f12CHF = new Money(12, "CHF"); f14CHF = new Money(14, "CHF"); } public void testSimpleAdd() { Money expected = new Money(26,"CHF"); Money results = f12CHF.add(f14CHF); Assert.assertTrue(expected.equals(results)); } Test Case
  • 11.
    public void testEquals() { Assert.assertTrue(!f12CHF.equals(null)); Assert.assertEquals(f12CHF, f12CHF); Assert.assertEquals(f12CHF, new Money (12, "CHF")); Assert.assertTrue(!f12CHF.equals(f14CHF)); } } Test Case
  • 13.
    @Test public void multiplicationOfZeroIntegersShouldReturnZero(){ // MyClass is tested MyClass tester = new MyClass(); // Tests assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0)); assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10)); assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0)); } Annotations
  • 14.
    package test; import junit.framework.TestSuite; publicclass TestRunner { public static void main(String[] args) { // the testcase String[] testCaseName = { MoneyTestCase.class.getName()}; // testrunner junit.swingui.TestRunner.main(testCaseName); //junit.textui.TestRunner.main(testCaseName); } } Test Case Runner
  • 15.
  • 16.
    public class TestContentextends TestCase { ContentServicecontentService; protected void setUp() throws Exception { contentService = new ContentService(); contentService.setMailGateway(new MailServerStub()); contentService.setContentDataGateway(new ContentDataGatewayStub()); } public void testService() throws ServiceException { contentService.addContent(new Content(1, "Video 1", "http", "", new D List<Content> list = contentService.getContents(); assertEquals(list.size(), 1); } Example
  • 17.
    Player Example ▪ Spring  Test  Framework   ▪ JUnit   ▪ PlayerService
  • 18.
  • 19.
    package is.ru.honn.rufan.domain;
 
 public classPlayer
 {
 protected int playerId;
 protected String username; protected String name;
 
 public Player()
 {
 }
 
 public Player(int playerId, String username, String name)
 {
 this.playerId = playerId;
 this.username = username;
 this.name = name;
 }
 ... Player Example
  • 20.
    package is.ru.honn.rufan.service;
 
 import is.ru.honn.rufan.domain.Player;
 
 publicinterface PlayerService
 {
 public int addPlayer(Player player) throws ServiceException;
 public Player getPlayer(int playerId);
 }
 Player Example
  • 21.
    package is.ru.honn.rufan.service;
 
 import is.ru.honn.rufan.domain.Player;
 importjava.util.ArrayList;
 import java.util.List;
 import java.util.logging.Logger;
 
 public class PlayerServiceStub implements PlayerService
 {
 Logger log = Logger.getLogger(PlayerServiceStub.class.getName());
 private List<Player> players = new ArrayList<Player>();
 
 Player Example
  • 22.
    public int addPlayer(Playerplayer) throws ServiceException
 {
 for(Player p: players)
 {
 if (p.getUsername() == player.getUsername())
 {
 String msg = "Username: '" + player.getUsername() + 
 "' already exists.";
 log.info(msg);
 throw new ServiceException(msg);
 }
 }
 
 players.add(player);
 return players.size()-1;
 }
 
 Player Example
  • 23.
    
 public Player getPlayer(intplayerId)
 {
 for(Player p: players)
 {
 if (p.getPlayerId() == playerId)
 return p;
 }
 
 return null;
 }
 
 }
 Player Example
  • 24.
  • 25.
    <?xml version="1.0" encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans beans/spring-beans.xsd"> <bean id="service" class="is.ru.honn.rufan.service.PlayerServiceStub" /> </beans> Player Example
  • 26.
    @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:app-test-stub.xml") public class testPlayerServiceextends TestCase { Logger log = Logger.getLogger(testPlayerService.class.getName()); @Autowired private PlayerService service; @Before public void setUp() { } Player Example
  • 27.
    @Test public void testUser() { Playerplayer0 = new Player(0, "messi", "Messi"); Player player1 = new Player(1, "ronaldo", "Ronaldo"); service.addPlayer(player0); service.addPlayer(player1); // Test if add works Player playerNew = service.getPlayer(1); assertSame(playerNew, player1); Player Example
  • 28.
    // Test ifsame username fails try { service.addPlayer(player1); } catch (ServiceException s) { assertSame(ServiceException.class, s.getClass()); } } } Player Example