2013-05-02 28 views
1
new MockUp<SomeClass>() { 
     @Mock 
     boolean getValue() { 
      return true; 
     } 
    }; 

我想根據測試用例從getValue()返回不同的值。我怎樣才能做到這一點?如何從不同情況下的模擬方法返回多個值?

+0

對每個測試用例製作新的模型或期望是否存在問題? – rees 2013-05-02 00:40:27

+0

你看過使用結果委託嗎? http://jmockit.googlecode.com/svn/trunk/www/tutorial/BehaviorBasedTesting.html#delegates – rees 2013-05-02 00:43:32

+0

我不知道如何在同一個類上創建同一個方法的多個mockUps。它只會執行第一個MockUp。 – alexD 2013-05-02 00:44:51

回答

3

要在不同的測試中具有與同一模擬類不同的行爲,您需要在的每個單獨測試中指定所需的行爲。例如,在這種情況下:

public class MyTest 
{ 
    @Test public void testUsingAMockUp() 
    { 
     new MockUp<SomeClass>() { @Mock boolean getValue() { return true; } }; 

     // Call code under test which then calls SomeClass#getValue(). 
    } 

    @Test public void anotherTestUsingAMockUp() 
    { 
     new MockUp<SomeClass>() { @Mock boolean getValue() { return false; } }; 

     // Call code under test which then calls SomeClass#getValue(). 
    } 

    @Test public void testUsingExpectations(@NonStrict final SomeClass mock) 
    { 
     new Expectations() {{ mock.getValue(); result = true; }}; 

     // Call code under test which then calls SomeClass#getValue(). 
    } 

    @Test public void anotherTestUsingExpectations(
     @NonStrict final SomeClass mock) 
    { 
     // Not really needed because 'false' is the default for a boolean: 
     new Expectations() {{ mock.getValue(); result = false; }}; 

     // Call code under test which then calls SomeClass#getValue(). 
    } 
} 

可以代替創建可重用MockUpExpectations子類,當然,但他們也將在需要的特定行爲每個測試實例化。

+0

這是我之前嘗試過的,但它從未執行過第二種情況下的模型。我認爲這是因爲我忘記了我在測試課上的另一個地方所做的整個班級的模擬。 – alexD 2013-05-02 17:56:28

相關問題