반응형
Dart 프로그램을 "수면"하려면 어떻게해야합니까?
테스트를 위해 Dart 애플리케이션에서 비동기 웹 서비스 호출을 시뮬레이션하고 싶습니다. 응답하는 모의 호출의 무작위성을 시뮬레이션하기 위해 (아마도 순서가 맞지 않음) 'Future'를 반환하기 전에 일정 시간 동안 대기 (수면)하도록 내 모의를 프로그래밍하고 싶습니다.
어떻게 할 수 있습니까?
Future.delayed 팩토리를 사용하여 지연 후 미래를 완료 할 수도 있습니다. 다음은 지연 후 비동기 적으로 문자열을 반환하는 두 함수의 예입니다.
import 'dart:async';
Future sleep1() {
return new Future.delayed(const Duration(seconds: 1), () => "1");
}
Future sleep2() {
return new Future.delayed(const Duration(seconds: 2), () => "2");
}
항상 원하는 것은 아니지만 (때로는 원하는 경우도 있음 Future.delayed
) Dart 명령 줄 앱에서 잠을 자고 싶다면 dart : io 's를 사용할 수 있습니다 sleep()
.
import 'dart:io';
main() {
sleep(const Duration(seconds:1));
}
Dart에는 코드 실행을 지연시키는 몇 가지 구현이 있다는 것을 알았습니다.
new Future.delayed(const Duration(seconds: 1)); //recommend
new Timer(const Duration(seconds: 1), ()=>print("1 second later."));
sleep(const Duration(seconds: 1)); //import 'dart:io';
new Stream.periodic(const Duration(seconds: 1), (_) => print("1 second later.")).first.then((_)=>print("Also 1 second later."));
//new Stream.periodic(const Duration(seconds: 1)).first.then((_)=>print("Also 1 second later."));
Dart 2+ 구문의 경우 비동기 함수 컨텍스트에서 :
import 'package:meta/meta.dart'; //for @required annotation
void main() async {
void justWait({@required int numberOfSeconds}) async {
await Future.delayed(Duration(seconds: numberOfSeconds));
}
await justWait(numberOfSeconds: 5);
}
이것은 오류를 모의하기 위해 선택적 매개 변수를 취할 수있는 유용한 모의입니다.
Future _mockService([dynamic error]) {
return new Future.delayed(const Duration(seconds: 2), () {
if (error != null) {
throw error;
}
});
}
다음과 같이 사용할 수 있습니다.
await _mockService(new Exception('network error'));
또한 단위 테스트 중에 서비스가 완료 될 때까지 기다려야했습니다. 이 방법으로 구현했습니다.
void main()
{
test('Send packages using isolate', () async {
await SendingService().execute();
});
// Loop to the amount of time the service will take to complete
for( int seconds = 0; seconds < 10; seconds++ ) {
test('Waiting 1 second...', () {
sleep(const Duration(seconds:1));
} );
}
}
...
class SendingService {
Isolate _isolate;
Future execute() async {
...
final MyMessage msg = new MyMessage(...);
...
Isolate.spawn(_send, msg)
.then<Null>((Isolate isolate) => _isolate = isolate);
}
static void _send(MyMessage msg) {
final IMyApi api = new IMyApi();
api.send(msg.data)
.then((ignored) {
...
})
.catchError((e) {
...
} );
}
}
참고 URL : https://stackoverflow.com/questions/18449846/how-can-i-sleep-a-dart-program
반응형
'IT TIP' 카테고리의 다른 글
jQuery AJAX 호출에서 '최종'과 유사한 것이 있습니까? (0) | 2020.11.26 |
---|---|
입력 텍스트 요소에 대한 올바른 읽기 전용 속성 구문은 무엇입니까? (0) | 2020.11.26 |
npm 오류! (0) | 2020.11.26 |
원본 어셈블리를 신뢰할 수 없기 때문에 MSTest 실행이 실패합니다. (0) | 2020.11.26 |
stdin에서 tar를 어떻게 만들 수 있습니까? (0) | 2020.11.26 |