国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

文章標(biāo)題

2019-11-10 20:02:52
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

先介紹下這篇博文的由來(lái),之前已經(jīng)對(duì)JUnit的使用經(jīng)行了深入的介紹和演示(參考JUnit學(xué)習(xí)(一),JUnit學(xué)習(xí)(二)),其中的部分功能是通過(guò)分析JUnit源代碼找到的。得益于這個(gè)過(guò)程有幸完整的拜讀了JUnit的源碼十分贊嘆作者代碼的精美,一直計(jì)劃著把源碼的分析也寫(xiě)出來(lái)。突發(fā)奇想決定從設(shè)計(jì)模式入手賞析JUnit的流程和模式的應(yīng)用,希望由此能寫(xiě)出一篇耐讀好看的文章。于是又花了些時(shí)日重讀《設(shè)計(jì)模式》以期能夠順暢的把兩者結(jié)合在一起,由于個(gè)人水平有限難免出現(xiàn)錯(cuò)誤、疏漏,還請(qǐng)各位高手多多指出、討論。

測(cè)試用例的一生——運(yùn)行流程圖

這里寫(xiě)圖片描述

圖一 TestCase運(yùn)行時(shí)序圖

首先,介紹下JUnit的測(cè)試用例運(yùn)行會(huì)經(jīng)過(guò)哪些過(guò)程,這里說(shuō)起來(lái)有些抽象會(huì)讓人比較迷惑,在看了后面章節(jié)的內(nèi)容之后就比較清晰了:

Client(JUnitCore、Eclipse):這里是TestCase開(kāi)始的地方,如果是Main函數(shù)來(lái)啟動(dòng)測(cè)試用例的話(huà)一般會(huì)調(diào)用JUnitCore的方法,如果是在Eclipse中使用JUnit插件則實(shí)際上調(diào)用的是org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference這個(gè)類(lèi)。 Request(org.junit.runner.Request):Client會(huì)根據(jù)測(cè)試類(lèi)或方法而創(chuàng)建一個(gè)Request實(shí)體,Request包含了要被執(zhí)行的測(cè)試類(lèi)、測(cè)試方法等信息。 RunnerBuilder:在創(chuàng)建后Client調(diào)用Request.getRunner()方法獲取用于執(zhí)行測(cè)試的Runner,該過(guò)程是由RunnerBuilder這個(gè)工廠(chǎng)類(lèi)完成的。 RunNotifier:在執(zhí)行Runner.run方法時(shí)Client還會(huì)傳遞一個(gè)RunNotifier對(duì)象,是事件的監(jiān)聽(tīng)器的管理員。Runner在開(kāi)始執(zhí)行、成功、失敗和執(zhí)行結(jié)束時(shí)會(huì)調(diào)用RunNotifier中相應(yīng)的方法從而發(fā)送事件給注冊(cè)了的監(jiān)聽(tīng)器,JUnit運(yùn)行的最終結(jié)果就是這些監(jiān)聽(tīng)器收集展現(xiàn)的。 Runner:從名字可以猜出這里應(yīng)該是測(cè)試用例運(yùn)行的地方了,在Client調(diào)用了Runner.run()方法之后,Runner會(huì)先構(gòu)造Statement對(duì)象將所有要執(zhí)行的邏輯委托給它,接著執(zhí)行Statement.evaluate()方法。在這期間Runner會(huì)觸發(fā)RunNotifier(如測(cè)試開(kāi)始、測(cè)試結(jié)束等等)。 Statement:測(cè)試用例的運(yùn)行時(shí)描述,關(guān)注于測(cè)試用例如何運(yùn)行和調(diào)用測(cè)試代碼。比如在執(zhí)行測(cè)試用例前是否有@Before注釋的方法需要調(diào)用等信息都會(huì)被Runner構(gòu)造為Statement。

JUnit的類(lèi)設(shè)計(jì)和模式應(yīng)用

這里寫(xiě)圖片描述

圖二 JUnit的類(lèi)結(jié)構(gòu)

首先先介紹下JUnit中的模型類(lèi)(Model),在JUnit模型類(lèi)可以劃分為三個(gè)范圍:

描述模型:是對(duì)要執(zhí)行的測(cè)試用例的描述(比如要執(zhí)行哪個(gè)類(lèi)的哪個(gè)方法,是否有指定Runner,使用了哪些注解等),這一層類(lèi)似于流程文件之于流程引擎——不是用來(lái)執(zhí)行的,而是描述要有哪些環(huán)節(jié)、細(xì)節(jié)。個(gè)人認(rèn)為這一模型包括測(cè)試類(lèi)本身(即你自己編寫(xiě)的測(cè)試用例)和Request。其中測(cè)試類(lèi)本身等同于描述文件,Request則記錄了是要運(yùn)行的Suit、測(cè)試類(lèi)或者是某個(gè)具體的方法、過(guò)濾器、排序的Comparator等信息(JUnit是支持對(duì)測(cè)試方法排序和過(guò)濾的)。運(yùn)行時(shí)模型:是JUnit中可執(zhí)行的模型,包括FrameworkMember(org.junit.runners.model.FrameworkMember)及其子類(lèi)、TestClass(org.junit.runners.model.TestClass)、Statement。FrameworkMember的子類(lèi)包括FrameworkMethod和FrameworkField分別描述了測(cè)試類(lèi)的方法和變量信息,比如是否為靜態(tài)、作用域、包含哪些注解等JUnit運(yùn)行時(shí)需要用到的信息;TestClass的作用有些類(lèi)似FrameworkMember,是針對(duì)測(cè)試的Class的描述。Statement在上面已經(jīng)介紹過(guò)是對(duì)測(cè)試執(zhí)行流程和細(xì)節(jié)的描述。

結(jié)果模型:JUnit中用于描述用例的類(lèi),包括Description(org.junit.runner.Description)、Result(org.junit.runner.Result)、Failure(org.junit.runner.notification.Failure)。Description是對(duì)測(cè)試用例的描述(測(cè)試名稱(chēng)、所在Class的名字、是否是suit等等)只為RunNotifier提供服務(wù)。Result是運(yùn)行結(jié)果的描述,用例執(zhí)行完成后RunNotifier的 fireTestRunFinished(final Result result)方法會(huì)被觸發(fā),傳入的Result實(shí)例描述了運(yùn)行耗時(shí)、忽略的用例次數(shù)、是否成功等信息。Failure則是用例失敗后Runner傳遞給RunNotifier的對(duì)象用于描述錯(cuò)誤信息,特別包含了錯(cuò)誤的StackTrace。 言歸正傳,下面討論設(shè)計(jì)模式和JUnit的源碼:

工廠(chǎng)方法模式、職責(zé)鏈:用例啟動(dòng),Client在創(chuàng)建Request后會(huì)調(diào)用RunnerBuilder(工廠(chǎng)方法的抽象類(lèi))來(lái)創(chuàng)建Runner,默認(rèn)的實(shí)現(xiàn)是AllDefaultPosibilitiesBuilder,根據(jù)不同的測(cè)試類(lèi)定義(@RunWith的信息)返回Runner。AllDefaultPosibilitiesBuilder使用職責(zé)鏈模式來(lái)創(chuàng)建Runner,部分代碼如下。代碼A是AllDefaultPosibilitiesBuilder的主要構(gòu)造邏輯構(gòu)造了一個(gè)【IgnoreBuilder->AnnotatedBuilder->SuitMethodBuilder->JUnit3Builder->JUnit4Builder】的職責(zé)鏈,構(gòu)造Runner的過(guò)程中有且只有一個(gè)handler會(huì)響應(yīng)請(qǐng)求。代碼B是Junit4Builder類(lèi)實(shí)現(xiàn)會(huì)返回一個(gè)BlockJUnit4ClassRunner對(duì)象,這個(gè)是JUnit4的默認(rèn)Runner。public Runner runnerForClass(Class<?> testClass) throws Throwable { List<RunnerBuilder> builders = Arrays.asList( ignoredBuilder(), annotatedBuilder(), suiteMethodBuilder(), junit3Builder(), junit4Builder()); for (RunnerBuilder each : builders) { Runner runner = each.safeRunnerForClass(testClass); if (runner != null) { return runner; } } return null; }

代碼A 職責(zé)鏈實(shí)現(xiàn)

public class JUnit4Builder extends RunnerBuilder { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { return new BlockJUnit4ClassRunner(testClass); }}

代碼B JUnit4Builder實(shí)現(xiàn)

組合模式:將具備樹(shù)形結(jié)構(gòu)的數(shù)據(jù)抽象出公共的接口,在遍歷的過(guò)程中應(yīng)用同樣的處理方式。這個(gè)模式在Runner中的應(yīng)用不是很明顯,扣進(jìn)來(lái)略有牽強(qiáng)。Runner是分層次的,父層包括@BeforeClass、@AfterClass、@ClassRule注解修飾的方法或變量,它們?cè)跍y(cè)試執(zhí)行前或執(zhí)行后執(zhí)行一次。兒子層是@Before、@After、@Rule修飾的方法或變量它們?cè)诿總€(gè)測(cè)試方法執(zhí)行前后執(zhí)行。當(dāng)編寫(xiě)的用例使用Suit來(lái)運(yùn)行時(shí)則是三層結(jié)構(gòu),上面的父子結(jié)構(gòu)中間插入了一層childrenRunners,也就是一個(gè)Suilt中每個(gè)測(cè)試類(lèi)都會(huì)生成一個(gè)Runner,調(diào)用順序變成了Runner.run()>childRunner.run()<即遍歷childrenRunners>->testMethod()。ParentRunner中將變化的部分封裝為runChild()方法交給子類(lèi)實(shí)現(xiàn),達(dá)到了遍歷過(guò)程使用同樣處理方式的目的——ParentRunner.this.runChild(each,notifier)。public void run(final RunNotifier notifier) { EachTestNotifier testNotifier = new EachTestNotifier(notifier, getDescription()); try { Statement statement = classBlock(notifier); statement.evaluate(); } catch (AssumptionViolatedException e) { testNotifier.fireTestIgnored(); } catch (StoppedByUserException e) { throw e; } catch (Throwable e) { testNotifier.addFailure(e); } } PRivate void runChildren(final RunNotifier notifier) { for (final T each : getFilteredChildren()) { fScheduler.schedule(new Runnable() { public void run() { ParentRunner.this.runChild(each, notifier); } }); } fScheduler.finished(); }

代碼C ParentRunner的組合模式應(yīng)用

模板方法模式:模板方法的目的是抽取公共部分封裝變化,在父類(lèi)中會(huì)包含公共流程的代碼,將變化的部分封裝為抽象方法由子類(lèi)實(shí)現(xiàn)(就像模板一樣框架式定好的,你去填寫(xiě)你需要的內(nèi)容就行了)。JUnit的默認(rèn)Runner——BlockJUnit4ClassRunner繼承自ParentRunner,ParentRunner類(lèi)定義了Statement的構(gòu)造和執(zhí)行流程,而如何執(zhí)行兒子層的runChild方法時(shí)交給子類(lèi)實(shí)現(xiàn)的,在BlockJUnit4ClassRunner中就是去構(gòu)造和運(yùn)行TestMethod,而另一個(gè)子類(lèi)Suit中則是執(zhí)行子層次的runner.run。

這里寫(xiě)圖片描述 圖三 RunNotifier的公共方法

private abstract class SafeNotifier { private final List<RunListener> fCurrentListeners; SafeNotifier() { this(fListeners); } SafeNotifier(List<RunListener> currentListeners) { fCurrentListeners = currentListeners; } void run() { synchronized (fListeners) { List<RunListener> safeListeners = new ArrayList<RunListener>(); List<Failure> failures = new ArrayList<Failure>(); for (Iterator<RunListener> all = fCurrentListeners.iterator(); all .hasNext(); ) { try { RunListener listener = all.next(); notifyListener(listener); safeListeners.add(listener); } catch (Exception e) { failures.add(new Failure(Description.TEST_MECHANISM, e)); } } fireTestFailures(safeListeners, failures); } } abstract protected void notifyListener(RunListener each) throws Exception; }public void fireTestRunStarted(final Description description) { new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testRunStarted(description); } ; }.run(); }

代碼D RunNotifier代碼截取

裝飾模式:保持對(duì)象原有的接口不改變而透明的增加對(duì)象的行為,看起來(lái)像是在原有對(duì)象外面包裝了一層(或多層)行為——雖然對(duì)象還是原來(lái)的類(lèi)型但是行為逐漸豐富起來(lái)。 之前一直在強(qiáng)調(diào)Statement描述了測(cè)試類(lèi)的執(zhí)行細(xì)節(jié),到底是如何描述的呢?代碼E展示了Statement的構(gòu)筑過(guò)程,首先是調(diào)用childrenInvoker方法構(gòu)建了Statement的基本行為——執(zhí)行所有的子測(cè)試runChildren(notifier)(非Suit情況下就是TestMethod了,如果是Suit的話(huà)則是childrenRunners)。接著是裝飾模式的應(yīng)用,代碼F是withBeforeClasses()的實(shí)現(xiàn)——很簡(jiǎn)單,檢查是否使用了@BeforeClasses注解修飾如果存在構(gòu)造RunBefores對(duì)象——RunBefore繼承自Statement。代碼H中的evaluate()方法可以發(fā)現(xiàn)新生成的Statement在執(zhí)行runChildren(fNext.evaluate())之前遍歷所有使用@BeforeClasses注解修飾的方法并執(zhí)行。產(chǎn)生的效果即使用@BeforeClasses修飾的方法會(huì)在所有用例運(yùn)行前執(zhí)行且只執(zhí)行一次。后面的withAfterClasses、withClassRules方法原理一樣都使用了裝飾模式,不再贅述。protected Statement classBlock(final RunNotifier notifier) { Statement statement = childrenInvoker(notifier); statement = withBeforeClasses(statement); statement = withAfterClasses(statement); statement = withClassRules(statement); return statement; } protected Statement childrenInvoker(final RunNotifier notifier) { return new Statement() { @Override public void evaluate() { runChildren(notifier); } }; }

代碼E Statement的構(gòu)造

protected Statement withBeforeClasses(Statement statement) { List<FrameworkMethod> befores = fTestClass .getAnnotatedMethods(BeforeClass.class); return befores.isEmpty() ? statement : new RunBefores(statement, befores, null); }

代碼F withBeforeClasses實(shí)現(xiàn)

public class RunBefores extends Statement { private final Statement fNext; private final Object fTarget; private final List<FrameworkMethod> fBefores; public RunBefores(Statement next, List<FrameworkMethod> befores, Object target) { fNext = next; fBefores = befores; fTarget = target; } @Override public void evaluate() throws Throwable { for (FrameworkMethod before : fBefores) { before.invokeExplosively(fTarget); } fNext.evaluate(); }}

代碼H RunBefores實(shí)現(xiàn)

策略模式:針對(duì)相同的行為在不同場(chǎng)景下算法不同的情況,抽象出接口類(lèi),在子類(lèi)中實(shí)現(xiàn)不同的算法并提供算法執(zhí)行必須Context信息。JUnit中提供了Timeout、ExpectedException、ExternalResource等一系列的TestRule用于豐富測(cè)試用例的行為,這些TestRule的都是通過(guò)修飾Statement實(shí)現(xiàn)的。修飾Statement的代碼在withRules()方法中實(shí)現(xiàn),使用了策略模式。代碼I描述了JUnit是如何處理@Rule標(biāo)簽的,withRules方法獲取到測(cè)試類(lèi)中所有的@Rule修飾的變量,分別調(diào)用withMethodRules和withTestRules方法,前者是為了兼容JUnit3版本的Rule這里忽略,后者withTestRules的邏輯很簡(jiǎn)單首先查看是否使用了@Rule,如存在就交給RunRules類(lèi)處理。代碼J是RunRules的實(shí)現(xiàn),在構(gòu)造函數(shù)中處理了修飾Statement的邏輯(applyAll方法)——抽象接口是TestRule,根據(jù)不同的場(chǎng)景(即使用@Rule修飾的不同的TestRule的實(shí)現(xiàn))選擇不同的策略(TestRule的具體實(shí)現(xiàn)),而Context信息就是入?yún)ⅲ╮esult:Statement, description:Description)。private Statement withRules(FrameworkMethod method, Object target, Statement statement) { List<TestRule> testRules = getTestRules(target); Statement result = statement; result = withMethodRules(method, testRules, target, result); result = withTestRules(method, testRules, result); return result; }private Statement withTestRules(FrameworkMethod method, List<TestRule> testRules, Statement statement) { return testRules.isEmpty() ? statement : new RunRules(statement, testRules, describeChild(method)); }

代碼I rule的執(zhí)行

public class RunRules extends Statement { private final Statement statement; public RunRules(Statement base, Iterable<TestRule> rules, Description description) { statement = applyAll(base, rules, description); } @Override public void evaluate() throws Throwable { statement.evaluate(); } private static Statement applyAll(Statement result, Iterable<TestRule> rules, Description description) { for (TestRule each : rules) { result = each.apply(result, description); } return result; }}

代碼J RunRules實(shí)現(xiàn)

這里簡(jiǎn)單舉一個(gè)Timeout的代碼。Timeout首先實(shí)現(xiàn)了TestRule方法并在apply中定義了自己的算法——構(gòu)造一個(gè)FailOnTimeout對(duì)象并返回。不再詳細(xì)描述FailOnTimeout的實(shí)現(xiàn),主要原理就是起一個(gè)線(xiàn)程來(lái)跑測(cè)試代碼并等待線(xiàn)程指定的時(shí)間,如果超時(shí)就會(huì)拋出異常。public class Timeout implements TestRule { private final int fMillis; /** * @param millis the millisecond timeout */ public Timeout(int millis) { fMillis = millis; } public Statement apply(Statement base, Description description) { return new FailOnTimeout(base, fMillis); }}

代碼K Timeout實(shí)現(xiàn)

外觀(guān)模式:封裝統(tǒng)一的對(duì)外接口,隱藏內(nèi)部各個(gè)小模塊之間的調(diào)用細(xì)節(jié),使得用戶(hù)既可以簡(jiǎn)單的使用facade來(lái)達(dá)到目的,必要時(shí)又可以自行操作內(nèi)部對(duì)象。這里的舉例可能不是非常明顯。圖四是TestClass的公共方法,代碼L給出了 TestClass(org.junit.runners.model.TestClass)的一小部分代碼,TestClass主要作用是封裝對(duì)Class的操作提供了JUnit運(yùn)行時(shí)需要用到的功能并隱藏其中操作的細(xì)節(jié)。在TestClass內(nèi)部將功能委托給了三個(gè)對(duì)象Class(java.lang.Class)、FrameworkMethod、FrameworkField來(lái)實(shí)現(xiàn),本身充當(dāng)了外觀(guān)(facade)對(duì)外提供了getName、getOnlyConstructor、getAnnotations等等接口,在必要的時(shí)又可以通過(guò)這個(gè)外觀(guān)獲取到Class、FrameworkMethod等對(duì)象。

這里寫(xiě)圖片描述

圖四 TestClass的公共方法

public class TestClass { private final Class<?> fClass; private Map<Class<?>, List<FrameworkMethod>> fMethodsForAnnotations = new HashMap<Class<?>, List<FrameworkMethod>>(); private Map<Class<?>, List<FrameworkField>> fFieldsForAnnotations = new HashMap<Class<?>, List<FrameworkField>>(); /** * Creates a {@code TestClass} wrapping {@code klass}. Each time this * constructor executes, the class is scanned for annotations, which can be * an expensive process (we hope in future JDK's it will not be.) Therefore, * try to share instances of {@code TestClass} where possible. */ public TestClass(Class<?> klass) { fClass = klass; if (klass != null && klass.getConstructors().length > 1) { throw new IllegalArgumentException( "Test class can only have one constructor"); } for (Class<?> eachClass : getSuperClasses(fClass)) { for (Method eachMethod : MethodSorter.getDeclaredMethods(eachClass)) { addToAnnotationLists(new FrameworkMethod(eachMethod), fMethodsForAnnotations); } for (Field eachField : eachClass.getDeclaredFields()) { addToAnnotationLists(new FrameworkField(eachField), fFieldsForAnnotations); } } } ……}

代碼L TestClass截取

寫(xiě)在最后

讀JUnit代碼時(shí)確實(shí)非常贊嘆其合理的封裝和靈活的設(shè)計(jì),自己雖然也寫(xiě)了幾年代碼但是在JUnit的源碼中收獲很多。由于對(duì)源碼的鉆研深度以及設(shè)計(jì)模式的領(lǐng)會(huì)不夠深入,文中有很多牽強(qiáng)和錯(cuò)誤的地方歡迎大家討論指正。最喜歡的是JUnit對(duì)裝飾模式和職責(zé)鏈的應(yīng)用,在看到AllDefaultPossiblitiesBuilder中對(duì)職責(zé)鏈的應(yīng)用還覺(jué)得設(shè)計(jì)比較合理,等到看到Statement的創(chuàng)建和組裝就感慨設(shè)計(jì)的精湛了,無(wú)論是基本的調(diào)用測(cè)試方法的邏輯還是@Before、@After等以及實(shí)現(xiàn)自TestRule的邏輯一并融入到Statement的構(gòu)造中,又不會(huì)牽扯出太多的耦合。總之無(wú)論是設(shè)計(jì)模式還是設(shè)計(jì)思想,歸根結(jié)底就是抽取公共部分,封裝變化,做到靈活、解耦。最后說(shuō)明這篇文章根據(jù)的源代碼是JUnit4.11的,maven坐標(biāo)如下,在JUnit的其它版本中源碼差別比較大沒(méi)有研究過(guò)。<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency>

轉(zhuǎn)自:junit源碼與設(shè)計(jì)模式欣賞


發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 扎兰屯市| 西峡县| 新安县| 招远市| 宜城市| 永仁县| 湖南省| 普洱| 弋阳县| 湖口县| 邵阳市| 雅江县| 城固县| 仪陇县| 澄迈县| 湘阴县| 桦川县| 英吉沙县| 曲周县| 观塘区| 新沂市| 华亭县| 怀远县| 井研县| 乐都县| 绥中县| 万盛区| 攀枝花市| 尼玛县| 庆安县| 灵璧县| 南华县| 东辽县| 南宫市| 石渠县| 盘山县| 吴旗县| 区。| 区。| 渭源县| 麻栗坡县|