На прошлой неделе мы с Джимом проделали небольшую работу, которая включала вызов URI состояния HA neo4j, чтобы проверить, является ли экземпляр master / slave, и мы использовали jersey-client .
Код выглядел примерно так:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
class Neo4jInstance { private Client httpClient; private URI hostname; public Neo4jInstance(Client httpClient, URI hostname) { this.httpClient = httpClient; this.hostname = hostname; } public Boolean isSlave() { String slaveURI = hostname.toString() + ":7474/db/manage/server/ha/slave"; ClientResponse response = httpClient.resource(slaveURI).accept(TEXT_PLAIN).get(ClientResponse.class); return Boolean.parseBoolean(response.getEntity(String.class)); }} |
При написании некоторых тестов для этого кода мы хотели оцепить фактические вызовы URI подчиненного HA, чтобы мы могли смоделировать оба условия, и краткий поиск показал, что mockito был подходящим вариантом .
В итоге мы получили тест, который выглядел так:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
|
@Testpublic void shouldIndicateInstanceIsSlave() { Client client = mock( Client.class ); WebResource webResource = mock( WebResource.class ); WebResource.Builder builder = mock( WebResource.Builder.class ); ClientResponse clientResponse = mock( ClientResponse.class ); when( builder.get( ClientResponse.class ) ).thenReturn( clientResponse ); when( clientResponse.getEntity( String.class ) ).thenReturn( "true" ); when( webResource.accept( anyString() ) ).thenReturn( builder ); when( client.resource( anyString() ) ).thenReturn( webResource ); assertTrue(isSlave);} |
что довольно грубо, но делает работу.
Я подумал, что должен быть лучший способ, поэтому я продолжил поиск и в конце концов наткнулся на это сообщение в списке рассылки, в котором предлагалось создать собственный ClientHandler и заглушить запросы / ответы.
Я попытался сделать это и обернул его небольшим DSL, который охватывает только наш очень специфический вариант использования:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
private static ClientBuilder client() { return new ClientBuilder();}static class ClientBuilder { private String uri; private int statusCode; private String content; public ClientBuilder requestFor(String uri) { this.uri = uri; return this; } public ClientBuilder returns(int statusCode) { this.statusCode = statusCode; return this; } public Client create() { return new Client() { public ClientResponse handle(ClientRequest request) throws ClientHandlerException { if (request.getURI().toString().equals(uri)) { InBoundHeaders headers = new InBoundHeaders(); headers.put("Content-Type", asList("text/plain")); return createDummyResponse(headers); } throw new RuntimeException("No stub defined for " + request.getURI()); } }; } private ClientResponse createDummyResponse(InBoundHeaders headers) { return new ClientResponse(statusCode, headers, new ByteArrayInputStream(content.getBytes()), messageBodyWorkers()); } private MessageBodyWorkers messageBodyWorkers() { return new MessageBodyWorkers() { public Map<MediaType, List<MessageBodyReader>> getReaders(MediaType mediaType) { return null; } public Map<MediaType, List<MessageBodyWriter>> getWriters(MediaType mediaType) { return null; } public String readersToString(Map<MediaType, List<MessageBodyReader>> mediaTypeListMap) { return null; } public String writersToString(Map<MediaType, List<MessageBodyWriter>> mediaTypeListMap) { return null; } public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> tClass, Type type, Annotation[] annotations, MediaType mediaType) { return (MessageBodyReader<T>) new StringProvider(); } public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> tClass, Type type, Annotation[] annotations, MediaType mediaType) { return null; } public <T> List<MediaType> getMessageBodyWriterMediaTypes(Class<T> tClass, Type type, Annotation[] annotations) { return null; } public <T> MediaType getMessageBodyWriterMediaType(Class<T> tClass, Type type, Annotation[] annotations, List<MediaType> mediaTypes) { return null; } }; } public ClientBuilder content(String content) { this.content = content; return this; }} |
Если мы изменим наш тест, чтобы использовать этот код, он теперь выглядит так:
|
1
2
3
4
5
6
7
8
9
|
@Testpublic void shouldIndicateInstanceIsSlave() { returns(200). content("true"). create(); assertTrue(isSlave);} |
Есть ли способ лучше?
В Ruby я использовал WebMock для достижения этой цели, и Ашок указал мне на WebStub, который выглядит неплохо, за исключением того, что мне нужно было бы передать имя хоста + порт, а не создавать его в коде.