函數(無副作用)是這樣一個基本的構建塊,但我不知道在Java中測試它們的令人滿意的方式。我該如何簡化Java中副作用免費方法的測試?
我正在尋找使測試更簡單的技巧。下面是我想要的一個例子:我在尋找一些註釋我可以把測試(S)
public void setUp() {
myObj = new MyObject(...);
}
// This is sooo 2009 and not what I want to write:
public void testThatSomeInputGivesExpectedOutput() {
assertEquals(expectedOutput, myObj.myFunction(someInput);
assertEquals(expectedOtherOutput, myObj.myFunction(someOtherInput);
// I don't want to repeat/write the following checks to see
// that myFunction is behaving functionally.
assertEquals(expectedOutput, myObj.myFunction(someInput);
assertEquals(expectedOtherOutput, myObj.myFunction(someOtherInput);
}
// The following two tests are more in spirit of what I'd like
// to write, but they don't test that myFunction is functional:
public void testThatSomeInputGivesExpectedOutput() {
assertEquals(expectedOutput, myObj.myFunction(someInput);
}
public void testThatSomeOtherInputGivesExpectedOutput() {
assertEquals(expectedOtherOutput, myObj.myFunction(someOtherInput);
}
,爲MyObject或myFunction的讓測試框架自動重複調用給myFunction在所有可能的排列爲給出的給定輸入/輸出組合,或可能排列的一些子集,以證明函數是有效的。
例如,上面的(僅)兩種可能的排列是:
- MyObj中=新的MyObject();
- myObj.myFunction(someInput);
- myObj.myFunction(someOtherInput);
和:
- MyObj中=新的MyObject();
- myObj.myFunction(someOtherInput);
- myObj.myFunction(someInput);
我應該只能提供輸入/輸出對(someInput,expectedOutput)和(someOtherInput,someOtherOutput),框架應該完成剩下的工作。
我還沒有使用QuickCheck,但它似乎是一個非解決方案。它被記錄爲一個生成器。我不是在尋找一種方法來爲我的函數生成輸入,而是一個框架,它允許我聲明性地指定我的對象的哪一部分是無副作用的,並使用基於該聲明的一些置換來調用我的輸入/輸出規範。
更新:我不想驗證對象中沒有任何更改,memoizing函數是這種測試的典型用例,並且memoizer實際上會更改其內部狀態。但是,給定一些輸入的輸出總是保持不變。
就這樣說,「隨機」和「測試」不會很好地結合在一起 - 您應該能夠重複完全相同的測試並獲得完全相同的結果,如果您使用隨機數而不是定義的輸入。你不希望一次測試失敗,因爲它使用了一個「壞」輸入,然後再傳一次,因爲該輸入不是測試的一部分。 – cHao 2010-08-09 07:14:41
刪除了隨機詞。我不是在尋找隨機的,我正在尋找所有排列的合理子集。 – user239558 2010-08-09 07:42:18
@cHao - 但是用一個固定的種子僞隨機並不是一個完全不好的想法......並且可以給你一個很好的排列子集。但坦率地說,我認爲這種測試對於檢查副作用是不合適的。 – 2010-08-09 07:43:31