티스토리 뷰

iOS/Test

테스트 응용 -Moya API Test-3

@서비 2022. 8. 24. 00:54

 

 

이제 마지막으로 테스트 코드를 작성해 본다.

 

moya 에서 제공하는 customEndpointClosure를 쓰면 별다른 조건 없이 샘플 데이터가 들어오는 것 처럼 동작 시킬 수 있다.

 

 

  func testExample() throws {
  
        let disposeBag = DisposeBag()
        
        //async 테스트를 위해 expectation 작성
        let expectation = XCTestExpectation()


		//moya에서 제공해주는 라이브러리로 실제 서버가 아닌 커스텀 엔드포인트를 만드는 과정이다.
        let customEndpointClosure = { (target: JokeAPI) -> Endpoint in
            return Endpoint(url: URL(target: target).absoluteString,
                            sampleResponseClosure: { .networkResponse(200, target.sampleData) },
                            method: target.method,
                            task: target.task,
                            httpHeaderFields: target.headers)
        }
 
		//provider 를 생성 할 때, 앞 서 작성한 커스텀 엔드 포인트를 넣어 준다.
        //immediatelyStub는 서버의 반응이 즉각 적인 옵션이고 0.5초나 2초도 있다.
        let testingProvider = MoyaProvider<JokeAPI>(endpointClosure: customEndpointClosure, stubClosure: MoyaProvider.immediatelyStub)
        
        testingProvider.rx.request(.randomJokes("GilDong","Hong"))
            .subscribe{ (result) in
                        switch result {
                        case .success(let response):
                            let result = try? response.map(Joke.self)
                            //응답 받은 값이 같은 지 확인 한다.
                            XCTAssertEqual(result?.value.joke, "GilDong Hong has 12 moons. One of those moons is the Earth." )
							
                        case .failure(let error):
                            print(error.localizedDescription)
                        }
                        //response 를 받으면 조건은 갖추어 진것으로 본다.
                        expectation.fulfill()

                    }
                    .disposed(by: disposeBag)
         	//2초 까지 기다린다.
		 wait(for: [expectation], timeout: 2.0)

    }

 

 

코드를 돌려보면 문제없이 성공 하는 것을 볼 수 있다.

sucess test

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함