1+ package org .baeldung .boot ;
2+
3+ import static org .junit .Assert .assertEquals ;
4+ import static org .junit .Assert .assertNotNull ;
5+ import static org .mockito .Matchers .anyInt ;
6+ import static org .mockito .Mockito .doReturn ;
7+
8+ import java .util .HashMap ;
9+ import java .util .Map ;
10+
11+ import org .baeldung .boot .components .FooComponent ;
12+ import org .baeldung .boot .model .Foo ;
13+ import org .junit .Before ;
14+ import org .junit .Test ;
15+ import org .junit .runner .RunWith ;
16+ import org .springframework .beans .factory .annotation .Autowired ;
17+ import org .springframework .boot .test .context .SpringBootTest ;
18+ import org .springframework .boot .test .context .SpringBootTest .WebEnvironment ;
19+ import org .springframework .boot .test .mock .mockito .SpyBean ;
20+ import org .springframework .boot .test .web .client .TestRestTemplate ;
21+ import org .springframework .http .HttpStatus ;
22+ import org .springframework .http .ResponseEntity ;
23+ import org .springframework .test .context .junit4 .SpringRunner ;
24+
25+ @ RunWith (SpringRunner .class )
26+ @ SpringBootTest (classes = DemoApplication .class , webEnvironment = WebEnvironment .RANDOM_PORT )
27+ public class FooComponentTests {
28+
29+ @ Autowired
30+ private TestRestTemplate testRestTemplate ;
31+
32+ @ SpyBean
33+ private FooComponent fooComponent ;
34+
35+ @ Before
36+ public void init () {
37+ Foo foo = new Foo ();
38+ foo .setId (5 );
39+ foo .setName ("MOCKED_FOO" );
40+
41+ doReturn (foo ).when (fooComponent ).getFooWithId (anyInt ());
42+
43+ // doCallRealMethod().when(fooComponent).getFooWithName(anyString());
44+ }
45+
46+ @ Test
47+ public void givenInquiryingFooWithId_whenFooComponentIsMocked_thenAssertMockedResult () {
48+ Map <String , String > pathVariables = new HashMap <String , String >();
49+ pathVariables .put ("id" , "1" );
50+ ResponseEntity <Foo > fooResponse = testRestTemplate .getForEntity ("/{id}" , Foo .class , pathVariables );
51+
52+ assertNotNull (fooResponse );
53+ assertEquals (HttpStatus .OK , fooResponse .getStatusCode ());
54+ assertEquals (5 , fooResponse .getBody ().getId ().longValue ());
55+ assertEquals ("MOCKED_FOO" , fooResponse .getBody ().getName ());
56+ }
57+
58+ @ Test
59+ public void givenInquiryingFooWithName_whenFooComponentIsMocked_thenAssertMockedResult () {
60+ Map <String , String > pathVariables = new HashMap <String , String >();
61+ pathVariables .put ("name" , "Foo_Name" );
62+ ResponseEntity <Foo > fooResponse = testRestTemplate .getForEntity ("/?name={name}" , Foo .class , pathVariables );
63+
64+ assertNotNull (fooResponse );
65+ assertEquals (HttpStatus .OK , fooResponse .getStatusCode ());
66+ assertEquals (1 , fooResponse .getBody ().getId ().longValue ());
67+ }
68+ }
0 commit comments