服务是调用实际类而不是模拟类。 Junit4和Jmock

时间:2015-04-06 01:19:02

标签: java 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();
}

}

这是调用实际的authenticate方法而不是mock authenticate类。有人能告诉我我做错了吗?

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

1 个答案:

答案 0 :(得分: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); 
相关问题