0

I am new to JUnit and Mockito. Can someone please guide how to mock the below rest template? My current mocking shows an error: Unfinished Stubbing.

Service

class MyService { void func(){ (SimpleClientHttpRequestFactory).restTemplate.getRequestFactory()).setConnectTimeout(t1); } } 

Mockito

Class MyTest { @Inject MyService service; @Mock RestTemplate template; @Test void testit(){ doNothing().when((SimpleClientHttpRequestFactory) .restTemplate.getRequestFactory())).setTimeout(anyInt(); } } 

1 Answer 1

1

You need to add initMocks() or openMocks() for mock initialisation like that:

@BeforeEach(for Junit5 @Before for Junit4) void setUp(){ initMocks(this); } 

And then you should declare your mocks behavior in the "when-then" section:

when(restTemplate.getRequestFactory()).thenReturn(mock(RequestFactory.class)); 

Use mockito for stubbing chain of invocation your methods.

Full version example:

Class MyTest { @Inject MyService service; @Mock RestTemplate template; @BeforeEach void setUp(){ initMocks(this); } @Test void testit(){ RestTemplate template = mock(RestTemplate.class); ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class); when(restTemplate.getRequestFactory()).thenReturn(template)); when(template.getRequestFactory).thenReturn(factory); etc... } 

}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.