title: Spring Controller Unit test, returning Null pointer exception
body: <p><strong>Im getting the following Error on running unit test for Spring controller: JavaNull pointer error In line :mockMvc.perform(MockMvcRequestBuilders.get(&quot;http://localhost:8080/1&quot;))</strong>
  My intention is to write unit test case for imagecontroller. Suggest any other alternative also. The image controller is taking image from Mysql database and rendering it in localhost server.</p>
  <p><strong>This is my ImageController class</strong></p>
  <pre><code>        @RestController
          @RequestMapping
          public class ImageController {
          @Autowired
          private ImageRepository imageRepository;
              // Return the image from the database using ResponseEntity
              @GetMapping(&quot;/{id}&quot;)
              public ResponseEntity&lt;byte[]&gt; fromDatabaseAsResEntity(@PathVariable(&quot;id&quot;) Integer id) throws 
              SQLException {
                  Optional&lt;DicomImage&gt; dicomimage = imageRepository.findById(id);
                  byte[] imageBytes = null;
                  if (dicomimage.isPresent()) {
                      imageBytes = dicomimage.get().getPhoto().getBytes(1,
                              (int) dicomimage.get().getPhoto().length());
                      System.out.print(imageBytes.length);
                  }
                  return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(imageBytes);
              }       
      }
  </code></pre>
  <p><strong>This is the ImageControllerTest class</strong></p>
  <pre><code>        @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
          class ImageControllerTest2 {
          @LocalServerPort
          private int port;
          @Autowired
          private TestRestTemplate restTemplate;
          private MockMvc mockMvc;
          @InjectMocks
          private ImageController imagecontroller;
          @Before
          public void setUp() throws Exception {
              mockMvc = MockMvcBuilders.standaloneSetup(imagecontroller).build();
          }
          @Test
          void test() throws Exception {
              mockMvc.perform(MockMvcRequestBuilders.get(&quot;http://localhost:8080/1&quot;))
              .andExpect(MockMvcResultMatchers.status().isOk())
              .andExpect(MockMvcResultMatchers.content().contentType(MediaType.IMAGE_JPEG));
              }
      }
  </code></pre>