SlideShare a Scribd company logo
JUnit

ksa-in project study
배경 지식
JUnit 이란?
JUnit 이란?
Unit testing framework for Java
Test Phases
• Unit testing on individual units of source
  code (= smallest testable part)

• Integration testing on groups of
  individual software modules

• System testing on a
  complete, integrated system (evaluate
  compliance with requirements)
TDD(Test Driven Development)
• Software Development Process
  – Family of Agile


• Test code를 작성하는 것이 소프트웨어 개
  발의 시작!

• Automated Test
TDD Process
       Refactor
                               Add a test
        code




                                        Run all
 Run the
                                      tests and
tests and
                                      see if the
see them
                                       new one
 succeed
                                         fails


                  Write some
                     code
Junit 4 뭐가 달라졌나?
import static com.wakaleo.gameoflife.domain.Cell.DEAD_CELL;
import static com.wakaleo.gameoflife.domain.Cell.LIVE_CELL;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
                                                        No need to extend TestCase
import org.junit.Test;

public class WhenYouCreateACell {
                                                       Annotation based
         @Test
         public void aLiveCellShouldBeRepresentedByAnAsterisk() {
                    Cell cell = Cell.fromSymbol("*");
                    assertThat(cell, is(LIVE_CELL));
         }                                            Call the tests anything you want

         @Ignore("Pending Implementation")            Annotations for test metadata
         @Test
         public void aDeadCellShouldBeRepresentedByADot() {
                    Cell cell = Cell.fromSymbol(".");
                    assertThat(cell, is(DEAD_CELL));
         }
         ...
}
일단 시작해봅시다!
간단한 test
간단한 test
고쳐보자
성공?
좀 더 복잡한 테스트
제대로 고치면 성공!
일단 Test는 짰는데 구현하기는 어렵고…
Test 할 때마다 빨간 막대기 보기 싫고…
@Before & @After
• @Before는 해당 클래스의 각각의 test가 실행되기 전에 동작(setup)
• @After는 해당 클래스의 각각의 test가 실행된 이후에 동작(tear
  down)


• @Before
  public void runBeforeEveryTest() {
      simpleMath = new SimpleMath();
  }

• @After
  public void runAfterEveryTest() {
      simpleMath = null;
  }
@BeforeClass & @AfterClass
• @BeforeClass는 해당 클래스의 test들이 시작되기 전 한 번 동작
  (setup)
• @AfterClass는 해당 클래스의 test가 모두 실행된 이후에 동작(tear
  down)


• @BeforeClass
  public static void runBeforeClass() {
      // run for one time before all test cases
  }

• @AfterClass
  public static void runAfterClass() {
      // run for one time after all test cases
  }
Exception Handling
• @Test(expected = <Exception 종류>
• 해당 Exception이 나야 test를 통과, Exception이 나지 않고 테스트가
  끝나면 fail


• @Test(expected = ArithmeticException.class)
  public void divisionWithException() {
      // divide by zero
      simpleMath.divide(1, 0);
  }
Timeout
• @Test(timeout = <시간, ms단위>)
• 해당 시간 내에 test가 끝나지 않으면 fail


• @Test(timeout = 1000)
  public void infinity() {
      while (true)
      ;
  }
유닛 테스트가 좋은건 알겠는데…
모든 메소드를 테스트 해야되나?
유닛 테스트가 좋은건 알겠는데…
모든 메소드를 테스트 해야되나?
    GET, SET 메소드도?
모범 답안
• Code를 쓰기 전에 Test를 씁시다

• 뭔가 깨질 껀덕지가 보이면 Test를 합시다.

• get, set 메소드처럼 깨지기엔 너무 간단한
  (too simple to break) 애들은 하지 말고요.

• Test code를 짰으면 자주 실행시킵시다.
Test Double
• Dummy objects are passed around but never actually used. Usually
  they are just used to fill parameter lists.

• Fake objects actually have working implementations, but usually
  take some shortcut which makes them not suitable for production
  (an in memory database is a good example).

• Stubs provide canned answers to calls made during the test, usually
  not responding at all to anything outside what's programmed in for
  the test. Stubs may also record information about calls, such as an
  email gateway stub that remembers the messages it 'sent', or
  maybe only how many messages it 'sent'.

• Mocks are objects pre-programmed with expectations which form a
  specification of the calls they are expected to receive.
Stub(1/2)
•   public interface MailService {
          public void send (Message msg);
    }
    public class MailServiceStub implements MailService {
          private List<Message> messages = new ArrayList<Message>();
          public void send (Message msg) {
                    messages.add(msg);
          }
          public int numberSent() {
                    return messages.size();
          }
    }
Stub(2/2)
•   class OrderStateTester...
          public void testOrderSendsMailIfUnfilled() {
                   Order order = new Order(TALISKER, 51);
                   MailServiceStub mailer = new MailServiceStub();
                   order.setMailer(mailer);
                   order.fill(warehouse);
                   assertEquals(1, mailer.numberSent());
          }
Mock
•   class OrderInteractionTester...
          public void testOrderSendsMailIfUnfilled() {
                   Order order = new Order(TALISKER, 51);
                   Mock warehouse = mock(Warehouse.class);
                   Mock mailer = mock(MailService.class);
                   order.setMailer((MailService) mailer.proxy());
                   mailer.expects(once()).method("send");
                   warehouse.expects(once()).method("hasInventory")
                             .withAnyArguments()
                             .will(returnValue(false));

                 order.fill((Warehouse) warehouse.proxy());
         }
    }
Reference
• Unit testing with JUnit
  – http://www.slideshare.net/tom.zimmermann/unit-
    testing-with-junit
• JUnit 4 in 60 seconds
  – http://www.cavdar.net/2008/07/21/junit-4-in-60-
    seconds/
• Mocks aren’t stubs
  – http://martinfowler.com/articles/mocksArentStubs.
    html#TheDifferenceBetweenMocksAndStubs

More Related Content

What's hot

xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
Chris Oldwood
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
automated-testing.info
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
Narendra Pathai
 
Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnit
inTwentyEight Minutes
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
Pranalee Rokde
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
Daniel Kolman
 
jUnit
jUnitjUnit
jUnit
sundar22in
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
akanksha arora
 
Junit 4.0
Junit 4.0Junit 4.0
Junit
JunitJunit
Test-Driven Development for TYPO3
Test-Driven Development for TYPO3Test-Driven Development for TYPO3
Test-Driven Development for TYPO3
Oliver Klee
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
vilniusjug
 
05 junit
05 junit05 junit
05 junit
mha4
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
Dinuka Malalanayake
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
Kissy Team
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
Kwangsoo Shin
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
Ravikiran J
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
Dror Helper
 

What's hot (20)

xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnit
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
jUnit
jUnitjUnit
jUnit
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Junit
JunitJunit
Junit
 
Test-Driven Development for TYPO3
Test-Driven Development for TYPO3Test-Driven Development for TYPO3
Test-Driven Development for TYPO3
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
05 junit
05 junit05 junit
05 junit
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 

Similar to J unit스터디슬라이드

Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
Erkin Ünlü
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
ICS
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
Devvrat Shukla
 
JUnit
JUnitJUnit
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Junit
JunitJunit
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
Amila Paranawithana
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
mudabbirwarsi
 
Junit
JunitJunit
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
Dmytro Patserkovskyi
 
Android testing
Android testingAndroid testing
Android testing
Sean Tsai
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
liminescence
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
Anton Udovychenko
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
Ortus Solutions, Corp
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
Srikrishna k
 

Similar to J unit스터디슬라이드 (20)

Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
JUnit
JUnitJUnit
JUnit
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Junit
JunitJunit
Junit
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
 
Junit
JunitJunit
Junit
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
 
Android testing
Android testingAndroid testing
Android testing
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 

J unit스터디슬라이드

  • 4. JUnit 이란? Unit testing framework for Java
  • 5. Test Phases • Unit testing on individual units of source code (= smallest testable part) • Integration testing on groups of individual software modules • System testing on a complete, integrated system (evaluate compliance with requirements)
  • 6. TDD(Test Driven Development) • Software Development Process – Family of Agile • Test code를 작성하는 것이 소프트웨어 개 발의 시작! • Automated Test
  • 7. TDD Process Refactor Add a test code Run all Run the tests and tests and see if the see them new one succeed fails Write some code
  • 8. Junit 4 뭐가 달라졌나? import static com.wakaleo.gameoflife.domain.Cell.DEAD_CELL; import static com.wakaleo.gameoflife.domain.Cell.LIVE_CELL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; No need to extend TestCase import org.junit.Test; public class WhenYouCreateACell { Annotation based @Test public void aLiveCellShouldBeRepresentedByAnAsterisk() { Cell cell = Cell.fromSymbol("*"); assertThat(cell, is(LIVE_CELL)); } Call the tests anything you want @Ignore("Pending Implementation") Annotations for test metadata @Test public void aDeadCellShouldBeRepresentedByADot() { Cell cell = Cell.fromSymbol("."); assertThat(cell, is(DEAD_CELL)); } ... }
  • 14. 좀 더 복잡한 테스트
  • 16. 일단 Test는 짰는데 구현하기는 어렵고… Test 할 때마다 빨간 막대기 보기 싫고…
  • 17. @Before & @After • @Before는 해당 클래스의 각각의 test가 실행되기 전에 동작(setup) • @After는 해당 클래스의 각각의 test가 실행된 이후에 동작(tear down) • @Before public void runBeforeEveryTest() { simpleMath = new SimpleMath(); } • @After public void runAfterEveryTest() { simpleMath = null; }
  • 18. @BeforeClass & @AfterClass • @BeforeClass는 해당 클래스의 test들이 시작되기 전 한 번 동작 (setup) • @AfterClass는 해당 클래스의 test가 모두 실행된 이후에 동작(tear down) • @BeforeClass public static void runBeforeClass() { // run for one time before all test cases } • @AfterClass public static void runAfterClass() { // run for one time after all test cases }
  • 19. Exception Handling • @Test(expected = <Exception 종류> • 해당 Exception이 나야 test를 통과, Exception이 나지 않고 테스트가 끝나면 fail • @Test(expected = ArithmeticException.class) public void divisionWithException() { // divide by zero simpleMath.divide(1, 0); }
  • 20. Timeout • @Test(timeout = <시간, ms단위>) • 해당 시간 내에 test가 끝나지 않으면 fail • @Test(timeout = 1000) public void infinity() { while (true) ; }
  • 21. 유닛 테스트가 좋은건 알겠는데… 모든 메소드를 테스트 해야되나?
  • 22. 유닛 테스트가 좋은건 알겠는데… 모든 메소드를 테스트 해야되나? GET, SET 메소드도?
  • 23. 모범 답안 • Code를 쓰기 전에 Test를 씁시다 • 뭔가 깨질 껀덕지가 보이면 Test를 합시다. • get, set 메소드처럼 깨지기엔 너무 간단한 (too simple to break) 애들은 하지 말고요. • Test code를 짰으면 자주 실행시킵시다.
  • 24. Test Double • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example). • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'. • Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
  • 25. Stub(1/2) • public interface MailService { public void send (Message msg); } public class MailServiceStub implements MailService { private List<Message> messages = new ArrayList<Message>(); public void send (Message msg) { messages.add(msg); } public int numberSent() { return messages.size(); } }
  • 26. Stub(2/2) • class OrderStateTester... public void testOrderSendsMailIfUnfilled() { Order order = new Order(TALISKER, 51); MailServiceStub mailer = new MailServiceStub(); order.setMailer(mailer); order.fill(warehouse); assertEquals(1, mailer.numberSent()); }
  • 27. Mock • class OrderInteractionTester... public void testOrderSendsMailIfUnfilled() { Order order = new Order(TALISKER, 51); Mock warehouse = mock(Warehouse.class); Mock mailer = mock(MailService.class); order.setMailer((MailService) mailer.proxy()); mailer.expects(once()).method("send"); warehouse.expects(once()).method("hasInventory") .withAnyArguments() .will(returnValue(false)); order.fill((Warehouse) warehouse.proxy()); } }
  • 28. Reference • Unit testing with JUnit – http://www.slideshare.net/tom.zimmermann/unit- testing-with-junit • JUnit 4 in 60 seconds – http://www.cavdar.net/2008/07/21/junit-4-in-60- seconds/ • Mocks aren’t stubs – http://martinfowler.com/articles/mocksArentStubs. html#TheDifferenceBetweenMocksAndStubs