资源描述
测试驱动的开发测试驱动的开发l测试驱动的开发l什么是测试驱动的开发l为什么要进行测试驱动的开发l如何进行测试驱动的开发传统测试方法及问题传统测试方法及问题l测试往往不够完整,会导致遗漏的错误;l测试往往由专门的测试人员实施,他们对程序的细节往往不够熟悉l测试人员通常根据文档,而不是代码来觉得究竟要测试哪些内容,而这些文档很容易过期而与代码不一致l大多数的测试是基于手工的,不能够自动完成,因此无法经常执行,即使重复执行往往也不能保证两次测试间的一致性。什么是测试驱动的开发什么是测试驱动的开发l先写单元测试用例,再写代码;l由测试来决定需要什么样的代码;l由程序员编写和维护完整的测试用例集;l仅当代码有了相应的测试代码,该代码才能作为成品代码;一个简单的演示一个简单的演示编写一个能够执行加法和减法的计算器测试驱动的开发的优点测试驱动的开发的优点l能够保证编写单元测试l使得程序员获得满足感,从而始终如一地坚持编写测试l有助于澄清接口和行为的细节l可证明、可再现、可自动验证l改变事物的信心测试驱动的开发的优点测试驱动的开发的优点l让计算机帮你记住l需要实现哪些类、接口和方法l哪些方法还没有实现或者还存在问题什么是什么是JUnitJUnitlJunit是一个测试框架,它的目标是简化单元测试的开发、运行和报告,主要包含以下的功能:l断言(assertions)l测试类和测试集(suites)l测试运行l测试结果报告l对于绝大多数的程序设计语言,都有类似的单元测试框架,他们统称为xUnit。开发开发JunitJunit单元测试的步骤单元测试的步骤l定义一个TestCase的子类.l重载setUp()或者 tearDown()方法(可选).l定义一个或者多个public testXXX()方法,在这个方法中:l操纵测试对象,包括创建对象、组装对象以及调用其中的方法l发起预期结果的断言.l随着测试用例的不断增加,可以创建一个TestSuite类,包含其他的测试用例。l对每一个类中的每一个公共方法(get/set方法除外),至少定义一个测试用例,如果该方法会抛出异常,则需要定义相应的异常测试用例。l可以定义一个main方法以便于该测试用例能够独立于开发环境或者其他工具而运行一个完整的测试用例一个完整的测试用例public class StringTest extends TestCase protected void setUp()/*run before*/protected void tearDown()/*after*/public void testSimpleEqual()String s1=new String(“abcd”);String s2=new String(“abcd”);assertTrue(“Strings not equal”,s1.equals(s2);public static void main(String args)junit.textui.TestRunner.run(suite();Assertions编写测试用例时的几点注意事项编写测试用例时的几点注意事项l使用setup()和 tearDown()来创建、初始化和释放测试用例间公共的测试对象及所需的环境。l确保测试没有副作用,也就是说测试用例运行前后系统的状态保持不变l确保测试用例间没有依赖关系,每一个测试用例都能够独立运行Course Sample public class StudentTest extends TestCase public void testTakeCourse()CourseEvaluationFactory system=CourseEvaluationFactory.getInstance();ICourse course=factory.createCourse(OOT,面向对象技术);IStudent student=factory.createStudent(001,test);int size=course.getStudents().size();student.takeCourse(course);assertEquals(size+1,course.getStudents().size();Course Samplepublic void testCourseNotAvaliable()CourseEvaluationFactory factory=CourseEvaluationFactory.getInstance();ICourse course=factory.createCourse(OOT,面向对象技术);try int i=0;for(;i course.getAllowStudents();i+)IStudent student=factory.createStudent(i,test);student.takeCourse(course);IStudent student=factory.createStudent(i+1test);student.takeCourse(course);fail(CourseNotAvailableException expected);catch(CourseNotAvailableException e)TestRunners l基于文本l轻量级,快速l从命令行启动java StringTestjava StringTest.Time:0.05Time:0.05Tests run:7,Failures:0,Errors:0Tests run:7,Failures:0,Errors:0TestRunners-Swingl图形界面,通过启动java junit.swingui.TestRunnerTestRunner:Eclipse IDETestRunner:Eclipse IDETestRunnit:.NETTestRunnit:.NET平台下的平台下的NUnitNUnitlWhen your test contains a failed assertion,Junit counts that as a failed testlWhen your test throws an exception(and does not catch it),Junit counts that as an error.lIf Junits test runners report the results of a test run in this format:“78 run,2 failures,1 error”From this you can conclude that 75 tests passed,2 failed and 1 was inconclusive.The difference between failures and errorslTest equals methodlTest a method that returns nothinglTest an interfacelTest throwing the right exceptionElementary testslThe mental model of test:The style of test caseThe style of test caseThe style of test caselProblemlYou want to test your implementation of equals()lBackgroundlequals()and hashCode()are important in Java object worldTest your equals methodRecipe:Using EqualsTesterWhy EqualsTester?Why EqualsTester?lProblemlYou want to test a method that has no return valuelBackgroundlA method has no return value has no direct way to determine what such a method does.Test a method that returns nothingCollection related methodlProblemlYou want to test an interface,but there is no way to instantiate an interface.You want to test more than just all the current implementations,you want to test all possible implementations.lBackgroundlWhen publishing an interface,the intent is usually to enforce a certain common behavior among all implementations of that interface.So test should be write to capture the requirements of the common behavior of the interface.Testing an interfaceRecipeRecipe(cont.)Example:ListIterator TestExample:ListIterator TestIteratorTestIteratorTestlProblemlYou want to verify that a method throws an excepted exception under the appropriate circumstances.lBackgroundlYou should know how JUnit decides whether a test passes or fails.Test Throwing the right exceptionRecipeRecipelTest a constructorlTest a getterlTest a setterOther elementary testslDeciding where to place production code and test codelDealing with duplicate test codelOrganizing special case testslBuilding tests in various development environmentsOrganizing and building Junit testslProblemlYou either do not wish to,or cannot,place test classes in a separate package from the production code under test.lBackgroundlMany Test-Driven practitioners prefer to place their test classes in a separate package from their production code.It is a good practice,but it is not always be applied.Place test classes in the same packagelWhen you write a test class,simply place it in the same package as the production code you plan to test.Your test will have access to all but the private parts of the production classs interface,allowing you to write tests for behavior that would otherwise remain hidden from you.Place test classes in the same packagelProblemlYou want to be able to easily distribute your production code separately from your test code.You would prefer not to confuse yourself or others by mixing up test code with production code.l BackgroundlAlthough we wish that programmers would ship their test code,it is still the norm to distribute production code without the corresponding tests.Create a separate source tree for test codeRecipelProblemlYou have written several tests for the same production class,and they contain duplicate code.Knowing that duplication is the root of all evil in software,you want to remove it.lBackgroundlThe objects under test is a test fixture.A configuration of objects whose behavior is easy to predict.So,the first part of a test the“create some objects”part can be called“create a fixture”.The goal is to create some objects and then initialize them to some known state so that you can predict their responses to invoking methods on them.Factor out a test fixturelIdentify the duplicated test fixture code in your tests.Move that code into a new method called setUp.Because each test executes in its own instance of your test case class,there is no need to worry about instance-level fields being set incorrectly from test to test.RecipeRecipeRecipelProblemlYou have multiple test fixtures that share some common objects.There objects are duplicated in the various TestCase classes that implement your fixture.You would like to reuse these objects,rather than duplicate them.lBackgroundlThis problem arises most frequently when writing customer tests of end-to-end tests that is,tests that target the entire system,rather than a simple class.Factor out a test fixture hierarchylIf you found test fixtures have common code,you can create a class hierarchy by extracting superclass.This can be done by following the next steps:RecipeRecipelProblemlYou have a common set of methods that you would like to use throughout your tests.It would be nice to refer to these methods as though they were part of the test case class,rather than as class-level methods on some utility class.lBackgroundlIt is very common over time to build up a sizable library of reusable utility methods for Junit tests.Perhaps the most common type of reusable method is the custom assertion.The assertion can be extracted into a base TestCaseIntroduce a Base Test CaselIntroduce a base test case that is,a class to act as the superclass for all your test case classes,which we often call BaseTestCase.Even if BaseTestCase has no methods to begin with,starting your project with a base test case provides a natural place of programmers to put any utility methods that they believe other tests will need to use.RecipelProblemlYou would like to build your tests using the command line,rather than relying on a full-featured IDElBackgroundlYou want a nightly buildlThe target operation system does not support your favorite IDEBuild tests from the command linelYou can run Junit in a command-line environment.RecipelProblemlYou need to build you tests in an environment where you cannot use your usual IDE.Youcan build the tests from the command line,but you would like to automate this task in a portable way.lBackgroundlThere is some serious limitations in using the Java compiler to build your tests:there is no direct support for building all the tests in your test source tree.It is difficult to implement some complicated building process using command-line tools.Build tests using AntRecipeDesigning for testinglTo test a component,you must be able to control its input(and internal state)and observe its output.If you cannot control the input,you cannot be sure what has caused a given output.If you cannot observe the output of a component under test,you cannot be sure how a given input has been processedDesign for testing lSeparation of interface and implementationlAllows substitution of implementation to testslFactory pattern(Or use IoC Container)lProvides for abstraction of creation of implementations from the tests.Design for testing-Mock ObjectslWhen your implementation requires a resource which is unavailable for testinglExternal system or database is simulated.lAnother use of Factory,the mock implementation stubs out and returns the anticipated results from a request.lDefinitionlA mock object is an object created to stand in for an object that your code will be collaborating with.Your code can call methods on the mock object,which will deliver results as set up by your tests.lMock objects are perfectly suited for testing a portion of code logic in isolation from the rest of the code.Mocks replace the objects with which your methods under test collaborate,thus offering a layer of isolation.Introducing mock objectslMake a bank transfer from one account to anotherMock tasting:a simple exampleClass under testAccountManager as InterfaceMockAccountManagerTest Case for AccountServicelWhats wrong with the following code:Using mock objects as a refactoring techniquelEasy refactoringUsing mock objects as a refactoring techniquelEasy refactoringUsing mock objects as a refactoring techniquelInversion of Control(IoC)lApplying the IoC pattern to a class means removing the creation of all object instances for which this class is not directly responsible and passing any needed instances instead.Design patterns in actionlSome people used to say that unit tests should be totally transparant to your code under test,and that you should not change runtime code in order to simplify testing.lThis is wrong.lUnit tests are first-class users of the runtime code and deserve the same consideration as any other user.Using mock objects as a refactoring techniquelThe biggest advantage of the mock-object approach is that it does not require a running container in order to execute the testslThe drawbacks of using mock objects are:lDo not test interactions with the container or between the componentslDo not test the deployment part of the componentslNeed excellent knowledge of the API being called in order to mock it,which can be difficultPros and cons of mock objectsSpellChecker例例l实现一个拼写检查的组件l该组件能够扩展为对不同类型的输入进行拼写检查,如文本文件,HTML文件等l该组件能够扩展为支持不同类型的语言.
展开阅读全文