2016-11-07 82 views
0

我正在嘲笑一個接口提交一些對象到遠程Http服務,邏輯如下:嘗試提交對象5次,如果提交成功,然後繼續下一個,否則嘗試,直到它達到5 - 然後丟棄如果仍然失敗。使用Mockito更改基於調用次數的模擬對象行爲?

interface EmployeeEndPoint { 

    Response submit(Employee employee); 

} 

class Response { 

    String status; 

    public Response(String status) { 
     this.status = status; 
    } 
} 


class SomeService { 

    private EmployeeEndPoint employeeEndPoint; 


    void submit(Employee employee) { 

     Response response = employeeEndPoint.submit(employee); 

     if(response.status=="ERROR"){ 
      //put this employee in a queue and then retry 5 more time if the call succeeds then skip otherwise keep trying until the 5th. 
     } 
    } 


} 

@Mock 
EmployeeEndPoint employeeEndPoint; 


@Test 
public void shouldStopTryingSubmittingEmployeeWhenResponseReturnsSuccessValue() { 
    //I want the first 

    Employee employee 
      = new Employee(); 
    when(employeeEndPoint.submit(employee)).thenReturn(new Response("ERROR")); 
    when(employeeEndPoint.submit(employee)).thenReturn(new Response("ERROR")); 
    when(employeeEndPoint.submit(employee)).thenReturn(new Response("SUCCESS")); 
    //I want to verify that when call returns SUCCESS then retrying stops ! 

    // call the service .. 


    verify(employeeEndPoint,times(3)).submit(employee); 
} 

現在的問題是我怎麼告訴模擬返回「ERROR」前兩次,並返回「SUCCESS」的第三次?

+0

我有點困惑:請您談一下JMock的,標記JMockit,但代碼看起來像Mockito。你能否澄清一下你使用的模擬框架? –

+0

@TimothyTruckle哦,男孩,我很抱歉。你是對的 !這是mockito! – Adelin

回答

1

標題告訴JMock的,標籤告訴JMockit

你的代碼看起來像的Mockito(而不是像JMock的也不JMockit),所以我假設你使用的Mockito儘管你在你的描述中寫道...

允許的Mockito你要麼枚舉順序或鏈中的返回值.then*()方法:

// either this 
when(employeeEndPoint.submit(employee)).thenReturn(
    new Response("ERROR"), 
    new Response("ERROR"), 
    new Response("SUCCESS") // returned at 3rd call and all following 
); 
// or that 
when(employeeEndPoint.submit(employee)) 
    .thenReturn(new Response("ERROR")) 
    .thenReturn(new Response("ERROR")) 
    .thenReturn(new Response("SUCCESS"));// returned at 3rd call and all following 
相關問題