szoftver tesztelés - gyakorlati jó-ha-tudod

55
Szoftver tesztelés Gyakorlati jó-ha- tudod Legéndi Richárd Olivér AITIA Szeminárium [email protected] http://people.inf.elte.hu/legendi / 2012. május 25.

Upload: richard-oliver-legendi

Post on 13-Jan-2015

769 views

Category:

Technology


4 download

DESCRIPTION

Céges szeminárium, körkép a használt tesztelő keretrendszerekről.

TRANSCRIPT

  • 1. Legndi Richrd Olivr AITIA Szeminrium [email protected]://people.inf.elte.hu/legendi/2012. mjus 25.

2. ttekintks Mirt? Honnan jn? Kik? Hogyan? Hol hasznljk aktvan? Mit kvetel meg? Toolok Ami belefr 3. Mirt? Quality Ami nektek, a fejlesztknek fontos: Bizalom a sajt kdodban Refactor: Nem flsz vltoztatni Nem fogod elbaszni, a teszted megfogja, ha valamit eltrtl! Hype tma, csapbl is ez folyi Boldog-boldogtalan tesztkrnyezeteket r Tanul tesztek, hatrvonalak tisztn tartsa, regressiontesztek (megoldott issue ne jhessen vissza), etc. 4. Honnan jn: RoR Agilis srcok Irgalmatlan egyszer hasznlni: test "login with invalid credentials" dopost :login => {:user_name => foo,:password =>bar}assert_equals flash[:error] , "Authentication failed"end 5. Kik? Tesztvezrelt-fejleszts (TDD) s a Behaviour Driven Development (BDD, vgrehajthat specifikci) elktelezett hvei (v.. eXtreme Programming: nincs terv, kdolnak egybl). 6. Hogyan?Forrs: http://www.javacodegeeks.com/2012/05/test-driven-development-win-win.html 7. Hogyan? A TDD hrom alapelve:1. Nem rsz tnyleges kdot, amg nem rtl hozz tesztet.2. A tesztbl annyit rsz meg, amennyi a kudarchoz elg (ha nem fordul pl., az mr kudarc).3. A tnyleges kdbl csak annyit rsz meg, ami elg a teszt sikeres teljestshez. TDD-ciklus: Test Code Refactor A teszt s production kd szimbizisban szletik 8. Milyen? F.I.R.S.T. alapelvek: Fast - Ha lass, nem futtatod. Independent - Ha fggsg van, hibt rejthet el. Repeatable - Brhol megismtelhet (minden fejlesztnl reproduklhat legyen a hiba). Self-validating - Ha kzzel kell hasonltgatnod a teszt eredmnyt, gysem fogsz vele foglalkozni. Timely - Rg nem tmogatott API funkcik tesztje teljesen felesleges. 9. Mit kvetel meg? A tervezst, kdstrukturt is talaktja. Kicsit ms kdszervezs kell(mellkhatsok elkerlse - azt nem tudod tesztelni) Sok POJO, minimlis funkcionalitssal(azt knny tesztelni) 10. Mit kvetel meg? Egyb aprsgok, pl. lazy instantiationt kidobni (premature optimalizci) Osztly nem vllalja fel a msodlagos feladatokat(Single Resp. Princ.) Helyette inkbb IoC/Dep. Inj.(AOP keretek, akkor hozza ltre, amikor kell) 11. Tesztek fajti Mindre nznk toolt: Unit: ~POJO-k Functional: ~project Integration: ~full stack Embedded DB + in-proc. web server + JWebUnit/Selenium Acceptance: ~user story 12. Toolok znvz (pun intended ) http://www.opensourcetesting.org/unit_java.php 70 kln lib/framework/tool... 13. Assert Lergott csont, de szerintem hasznos Control-flow invariant, etc. Nem egy DbC facility, de hasznos: Internal Invariants Control-Flow Invariants Preconditions, Postconditions, and Class Invariantshttp://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html 14. Unit tesztek Egysgek (pl. modellek) tesztelsre Tonnnyi keretrendszer (JUnit/TestNG/...) Kent Beck (XP megalkotja, Agile demigod), Erich Gamma (hasonl kaliber riember, pl. Eclipse JDT- ben volt benne a keze) haxolta ssze egy replgpen a JUnit els verzijt. 15. Pldapublic class Utils {public static int sum(int[] arr) {if (null == arr) {throw new IllegalArgumentException("arr == null");}int sum = 0;for (int i : arr) {sum += i;}return sum;}} 16. Tesztek (JUnit 4.x)import org.junit.* ;import static org.junit.Assert.* ;public class UtilsTest {@Testpublic void assertSumForZeroArray() {final int[] arr = new int[0];// Givenfinal int actual = Utils.sum(arr); // Whenfinal int expected = 0; // ThenassertEquals("Sum of empty array must be zero.", expected, actual);}@Test(expected=IllegalArgumentException.class)public void assertForIllegalArgument() {Utils.sum(null);}} 17. Egyb hasznos annotcik@Ignore("John broke this yesterday")@Test(timeout=1000)@Test public voidpublic void someMethodThatShouldRunInAMinute() {someBuggyOrUnimplementedTest() {// ...// ...}}@Before@BeforeClasspublic void beforeEachTest() {public void initializeStuffBeforeAnyTests() { // ...// ...}}@After@AfterClass public void afterEachTest() {public void cleanupStuffAfterAllTests() { // ...// ...}} 18. Egyb hasznos assert utastsok assertTrue(...); Tonnnyi egyb assertFalse(); Ld. Assert javadoc fail(); assertEquals(...); assertArrayEquals(...); assertEquals(...); assertNotNull(...); assertNull(...); assertSame(...); assertNotSame(...); assertEquals(...); assertThat(...); // Matcher 19. Common Pitfalls Egy teszt-egy llts (nem felttlen egy assert utasts) Teszttel is jtsz egy kicsit! Az is kd, abban is annyira bzz... Trivilis tesztek! Trivilis hibakeress Ajnls: tnyleges kd s a tesztek kln source mappban(production kdban semmi helye, tisztessges build tooloknl ezalap) Lthatsg: a legritkbb esetben oldjuk fel tesztek miatt. Legyenez az utols, amivel prblkozunk! Vigyzat, 2 JUnit osztly van! A msik legacy... Randomizls? Inkbb ne... Mutation testing assertTrue(actual == 0) !=assertEquals(expected, actual) 20. IDE Integrci Eclipse Hozzads: Project jobklikk -> Properties -> Java Build Path -> Libraries -> Add Library -> JUnit -> JUnit 4 (alapbl benne van) Futtats: Jobklikk -> Run As... -> JUnit NetBeans Alapbl benne van egy egyszer Java projectben. 21. Egyb Toolok 22. Mocking Motivci: adatbzis nincs... DAO-s plda: van interfsz, van JdbcDaoimplementci, aztn meg Test1Dao implementci... DE! Helyette: lehet mockolni, gyes cuccok(Nha mr-mr internal DSL benyomst kelt toolok) Ebbl is van egy pr... 23. Mocking frameworkk zelthttp://code.google.com/p/jmockit/wiki/MockingToolkitComparisonMatrix 24. Mocking: Pldapublic void testBobsLogin() {User results = new User();String userName = "bob";String password = "bob1234";String passwordHash = "0340e21833f1291f673fcaab8d13";expect(mockDao.queryUserData(userName, passwordHash)).andReturn(results);replay(mockDao);assertTrue(service.login(userName, password));verify(mockDao);} 25. Tonnnyi egyb feature Ellenrzsek Hvsok min/max/pontos szma Sorrendisg Rszleges mockols Spy: adott fggvnyek kitsre Viselkeds felvtele, visszajtszsa, ellenrzse ... 26. PowerMock Ha elrtk a korltokat, "j lenne..." funkcik Tmogat tbb platformot Mockito/EasyMock/... Pldk: statikus fggvnyek mockolsa final classok mockolsa ... 27. Hamcrest Matcher library (innen a nv) "Literate programming" (Knuth, 1970) Pldval a legknnyebb megrteni: assertThat("Ray went to holiday",developers.getRay().countReadBooks(), equalTo(10)); assertThat(Math.sqrt(-1), is(notANumber())); A BDD-s srcok nagyon szeretik Knyelmi funkcionalitsa van 28. Design by Contract Eiffel Bertrand Meyer Minden komponensnek contractja van(Nem is ll olyan messze tlnk, ld. equals(), hashCode()Javadocjt!) Ebbl is van tonnnyi, 3 plda: comment, annotcis, konfigurcis osztlyos Invarins, el- s utfelttelek Assertekkel kivlthat? Nem igazn... AspectJ-vel lehet jtszani egy szintig, de... Hol hasznos? Pl. szervleteknl ott, ahol macera a tesztels 29. Plda@Invariant("getCount() >= 0")public interface Stack {int getCount();...@Ensure("{result}==(getCount()==0)")public boolean isEmpty();@Require("getCount() > 0 ")@Ensure("getCount() == {old getCount()} - 1 ")void remove();} 30. Code coverage Nagyobb projectnl knny elveszteni, mit mennyireteszteltnk Megolds: Code coverage (szmtalan definci szerint) Reneteg tool, pl. Clover, Cobertura (generlt doksikkirlyak) Vannak pluginok az IDE-kben, pl. EclEmma 31. Code coverage Maximizlni rdemes, nem rdemes? Nem biztos, hogy megri a 100%-ra hajtani - br lttam mr ilyet (s nem is mindig megoldhat, pl. BufferedReadert megfelelen hasznlni lehetetlen) Nha meg a 400% is kevs... Koncentrljunk a lnyeges komponensekre 32. Continuous Integration rendszerek Rengeteg tool: Hudson, Jenkins, Bamboo, ... Mikor? Ha sok teszt van, s nem elg a GridGain farm pl.Unit tesztek gyorsan lefutnak, de lehetnek sokan. Integrci! pl. cm/inch Kaphat/pthet build status jelz http://hackaday.com/2011/04/12/led-build-monitor-helps-keep-an-eye-on-your-servers/ 33. Sonar Mindenfle statisztikk - a trend miatt fontos. sszektve a CI rendszerrel Mutatja a tesztelsre szorul rszeket Tonnnyi projecthez plda: http://nemo.sonarsource.org/ 34. Acceptance tesztek Rengeteg tool, framework, pl. FitNesse, Specs2 Decision table egy Wikibe Teszt, minimlis kddal truhzhat a tesztrs a kliensre Haha... 35. Plda: FitNesse Wiki: |eg.Division| |numerator|denominator|quotient?| |10 |2|5| |12.6 |3|4.2| |100|4|33 | Kell hozz egy minimlis Java osztly, 3 adattaggal Lesz egy nagy zld Teszt gomb Meg lehet nyomni Plda: http://fitnesse.org/FitNesse.UserGuide.TwoMinuteExample 36. Plda: Specs2 Forms 37. BDD Wiki: BDD is a second-generation, outsidein, pull-based,multiple-stakeholder, multiple-scale, high-automation,agile methodology. It describes a cycle of interactionswith well-defined outputs, resulting in the delivery ofworking, tested software that matters. Magyarul: rtse meg a nem kder is a teszteket 38. DSL Scala, Specs1/2 class HelloWorldSpec extends Specification { "The Hello world string" should { "contain 11 characters" in { "Hello world" must have size(11) } "start with Hello" in { "Hello world" must startWith("Hello") } "end with world" in { "Hello world" must endWith("world") } } } Forrs: http://etorreborre.github.com/specs2/ 39. DSL Scala, Specs2import org.specs2._class HelloWorldSpec extends Specification { def is ="This is a specification to check the Hello world string" ^p^"The Hello world string should" ^"contain 11 characters" ! e1^"start with Hello"! e2^"end with world"! e3^enddef e1 = "Hello world" must have size(11)def e2 = "Hello world" must startWith("Hello")def e3 = "Hello world" must endWith("world")} 40. DSL Groovy (Spock)@Unrollvoid "Ship goes to red alert only when enemy charges weapons"() {given:CommandComputer commandComputer = new CommandComputer()and: ~JUnit Theories, de egyszerbbwhen:szintakszissalcommandComputer.updateFromSensors(sensorReading)Forrs: http://sett.ociweb.com/sett/settFeb2012.htmlthen:commandComputer.getAlertStatus() == expectedAlertStatuswhere:entityType