Last active
November 5, 2019 10:10
-
-
Save itzurabhi/b506d2179596c3ad7dfbf75d0275c0af to your computer and use it in GitHub Desktop.
Dart Interface Based Mocking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "dart:async"; | |
class LoginRequest {} | |
class LoginResponse { | |
String code; | |
LoginResponse(this.code); | |
} | |
class LogoutRequest {} | |
class LogoutResponse {} | |
class APIError { | |
String message; | |
num code; | |
APIError(this.message, this.code); | |
} | |
var InternalError = APIError("This is a sample internal error", 500); | |
class IServerAPI { | |
Future<LoginResponse> Login(LoginRequest req) { | |
return null; | |
} | |
Future<LogoutResponse> LogOut(LogoutRequest req) { | |
return null; | |
} | |
} | |
class SuccessServerAPI implements IServerAPI { | |
@override | |
Future<LogoutResponse> LogOut(LogoutRequest req) { | |
return Future.value(LogoutResponse()); | |
} | |
@override | |
Future<LoginResponse> Login(LoginRequest req) { | |
return Future.value(LoginResponse("this is the code")); | |
} | |
} | |
class LoginErrorAPI implements IServerAPI { | |
@override | |
Future<LogoutResponse> LogOut(LogoutRequest req) { | |
return Future.value(LogoutResponse()); | |
} | |
@override | |
Future<LoginResponse> Login(LoginRequest req) { | |
return Future.error(InternalError); | |
} | |
} | |
class SlowAPI implements IServerAPI { | |
@override | |
Future<LogoutResponse> LogOut(LogoutRequest req) async { | |
await Future.delayed(const Duration(seconds: 1), () { | |
print("delay complete"); | |
}); | |
return Future.value(LogoutResponse()); | |
} | |
@override | |
Future<LoginResponse> Login(LoginRequest req) async { | |
await Future.delayed(const Duration(seconds: 1), () { | |
print("delay complete"); | |
}); | |
return Future.value(LoginResponse("200")); | |
} | |
} | |
void main() async { | |
IServerAPI api = SuccessServerAPI(); | |
var inRes = await api.Login(LoginRequest()); | |
print(inRes.code); | |
var outRes = await api.LogOut(LogoutRequest()); | |
print(outRes); | |
api = LoginErrorAPI(); | |
try { | |
inRes = await api.Login(LoginRequest()); | |
print(inRes); | |
} on APIError catch (err) { | |
print(err.message + " " + err.code.toString()); | |
} catch (e) { | |
print(e); | |
} | |
api = SlowAPI(); | |
try { | |
inRes = await api.Login(LoginRequest()); | |
print(inRes); | |
outRes = await api.LogOut(LogoutRequest()); | |
print(outRes); | |
} on APIError catch (err) { | |
print(err.message + " " + err.code.toString()); | |
} catch (e) { | |
print(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment