Jav
Jav

Reputation: 115

How to write Mock test cases for Webtarget and Response for a rest client?

WebTarget resource = clientLocal.target(/test/url))
Response response = resource.request(MediaType.APPLICATION_JSON)
                    .header("Content-type", MediaType.APPLICATION_JSON)
                    .header("Authorization", "Basic"+" "+"234YML")
                    .post(Entity.entity("", MediaType.TEXT_PLAIN), Response.class);
responseEntity = response.readEntity(Test.class);

When Response object is mocked, builder object for Authorization header is returning null,

Mockito.when(mockWebTarget.request(MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
Mockito.when(mockBuilder.header("Content-type", MediaType.APPLICATION_JSON))
        .thenReturn(mockBuilder);
Mockito.when(mockBuilder.header("Authorization",eq(anyString())))
        .thenReturn(mockBuilder);
Mockito.when(mockBuilder.post(Entity.entity(anyString(), MediaType.TEXT_PLAIN), eq(Response.class)))
        .thenReturn(mockResponse);

How the second part of header should be mocked so that it does not return null value?

Upvotes: 3

Views: 4528

Answers (1)

Nkosi
Nkosi

Reputation: 247511

eq(anyString()) is the problem in

Mockito.when(mockBuilder.header("Authorization",eq(anyString())))
    .thenReturn(mockBuilder);

It should be

Mockito.when(mockBuilder.header(eq("Authorization"), anyString()))
    .thenReturn(mockBuilder);

The argument matcher eq is used for literal matches.

Also if you are using argument matchers, all arguments have to be provided by matchers.

The first one worked because all the arguments were literal values.

That would also mean that

Mockito.when(mockBuilder.post(Entity.entity(anyString(), MediaType.TEXT_PLAIN), eq(Response.class)))
    .thenReturn(mockResponse);

needs to change to

Mockito.when(mockBuilder.post(any(Entity.class), eq(Response.class)))
    .thenReturn(mockResponse);

Upvotes: 2

Related Questions