2015-04-06 32 views
1

我已經檢查了所有現有的堆棧溢出問題。但我找不到合適的解決方案。服務正在調用實際類而不是模擬類。 Junit4和Jmock

public class TestAuthenticate { 
private RestService rs; 
private String token_actual = token1; 
private Mockery context; 
private Authenticate authenticate_object; 


@Before 
public void setup(){ 
context = new JUnit4Mockery() {{ 
    setImposteriser(ClassImposteriser.INSTANCE); 
}}; 

rs = new RestService(); 
} 

@Test 
public final void testAuthenticate() { 

    authenticate_object = context.mock(Authenticate.class); 

    context.checking(new Expectations() { 
     { 
      oneOf(authenticate_object).authenticate_method("username", "password"); 
      will(returnValue(token1)); 
     } 
    }); 
    String token = rs.authenticate("username", "password"); 
    System.out.println(token); 

    assertEquals(token_actual, token); 
    context.assertIsSatisfied(); 
} 

}

這是調用實際身份驗證方法,而不是模擬身份驗證類。有人能告訴我我做錯了什麼嗎?

public class RestService { 
public string authenticate(String user, String pass){ 
Authenticate auth = new Authenticate(); 
String res = auth.authenticate(user,pass); 
} 
return res; 
} 
+1

我沒有看到任何地方,你傳遞了'authenticate'對象的任何東西。 「RestService」應該如何得到它? – chrylis 2015-04-06 01:21:35

+0

請查看我更新的代碼。 Rest服務具有調用Authenticate對象的身份驗證方法 – Jenny 2015-04-06 01:48:19

+1

否...每次調用該方法時,都會實例化一個新的Authenticate。我想知道JMock是否具有與Mockito相同的功能,在Mockito中可以實際模擬新的呼叫。 – Makoto 2015-04-06 01:49:43

回答

0

通常,您會使用某種形式的依賴注入將模擬AuthenticationService注入到RestService中。請嘗試重寫你的RestService一樣,

public class RestService { 
    private final AuthenticateService auth; 
    public RestService(AuthenticateService auth) { 
     this.auth = auth; 
    } 
    public string authenticate(String user, String pass){ 
     return auth.authenticate(user,pass); 
    } 
} 

然後在您的測試做

rs = new RestService(authenticate_object); 
+0

我這樣做了,但我有7種方法,我不能寫7個構造函數。同樣在每種方法中,令牌都是作爲參數。所以我必須再次調用每種方法的身份驗證。還有其他解決方案嗎? – Jenny 2015-04-06 22:35:32

相關問題