2011-09-08 37 views

回答

7

編輯:繼JUnit 4.11發佈後,您現在可以使用@Rule註釋方法。

你會使用它像:

private TemporaryFolder folder = new TemporaryFolder(); 

@Rule 
public TemporaryFolder getFolder() { 
    return folder; 
} 

對於較早版本的JUnit,請參閱下面的答案。

-

不,你不能直接從Scala的使用。該領域需要是公開的和非靜態的。從 org.junit.Rule

public @interface Rule: Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule.

你不能聲明Scala中的一個公共領域。所有字段都是私有的,並且可以通過訪問者訪問。請參閱question的答案。

除了這一點,也已經是JUnit的一個增強請求(仍處於打開狀態):

Extend rules to support @Rule public MethodRule someRule() { return new SomeRule(); }

另一種選擇是,非公有制領域是允許的,但是這已經被拒絕:Allow @Rule annotation on non-public fields

那麼你的選擇是:

  1. 克隆JUnit和實施的第一個建議,方法,並提交pull請求
  2. 從實現的@rule java類擴展斯卡拉類

-

public class ExpectedExceptionTest { 
    @Rule 
    public ExpectedException thrown = ExpectedException.none(); 
} 

,然後從該繼承:

class ExceptionsHappen extends ExpectedExceptionTest { 

    @Test 
    def badInt: Unit = { 
    thrown.expect(classOf[NumberFormatException]) 
    Integer.parseInt("one") 
    } 
} 

它能正常工作。

+1

爲清楚:它(現在)的作品在斯卡拉(但只方法:'@rule高清MyRule的= ...'不帶屬性,如'@規則val myRule = ...') –

0

不知道JUnit規則,而沒有測試它,因爲我手頭沒有合適的設置,所以我會出現在肢體上,並建議將它轉換爲val。 我想它的一些成員是用某種東西初始化的,然後它得到一些狀態,然後一些其他的機器檢查狀態。你總是在創造新的東西,並忘記期待。

0

如果Scala具有類似靜態導入類似的東西,那麼catch-exception是JUnit 4.7的ExpectedException @Rule的替代方案。

6

爲了使這個工作與JUnit 4。11 在斯卡拉,你應該讓只適用於(合成)getter方法的註解元註解你的註釋,而不是基本的領域:

import org.junit._ 
import scala.annotation.meta.getter 

class ExceptionsHappen { 

    @(Rule @getter) 
    def thrown = rules.ExpectedException.none 

    @Test 
    def badInt: Unit = { 
    thrown.expect(classOf[NumberFormatException]) 
    Integer.parseInt("one") 
    } 
} 
0

作爲一個非常新手斯卡拉我只是用一個非常簡單的解決方法:明確地捕獲異常並在未拋出預期的異常時失敗。

下面是一個示例骨架:

try { 
    *your code that should throw an exception* 
    fail("Did not generate *the.Exception.you.expect*") 
} catch { 
    case t: *the.Exception.you.expect* => // do nothing, it's expected :) 
} 
相關問題