1 /* 2 * Copyright (C) 2012 Square, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.squareup.okhttp.internal.http; 17 18 import com.squareup.okhttp.Dns; 19 import java.net.InetAddress; 20 import java.net.UnknownHostException; 21 import java.util.ArrayList; 22 import java.util.Arrays; 23 import java.util.Collections; 24 import java.util.List; 25 26 import static org.junit.Assert.assertEquals; 27 28 public final class FakeDns implements Dns { 29 private List<String> requestedHosts = new ArrayList<>(); 30 private List<InetAddress> addresses = Collections.emptyList(); 31 32 /** Sets the addresses to be returned by this fake DNS service. */ addresses(List<InetAddress> addresses)33 public FakeDns addresses(List<InetAddress> addresses) { 34 this.addresses = new ArrayList<>(addresses); 35 return this; 36 } 37 38 /** Sets the service to throw when a hostname is requested. */ unknownHost()39 public FakeDns unknownHost() { 40 this.addresses = Collections.emptyList(); 41 return this; 42 } 43 address(int index)44 public InetAddress address(int index) { 45 return addresses.get(index); 46 } 47 lookup(String hostname)48 @Override public List<InetAddress> lookup(String hostname) throws UnknownHostException { 49 requestedHosts.add(hostname); 50 if (addresses.isEmpty()) throw new UnknownHostException(); 51 return addresses; 52 } 53 assertRequests(String... expectedHosts)54 public void assertRequests(String... expectedHosts) { 55 assertEquals(Arrays.asList(expectedHosts), requestedHosts); 56 requestedHosts.clear(); 57 } 58 } 59