title: JUnit to retrieve value from database to test criteria
body: <p>How do I write JUnit with actual service/repository call to retrieve data from a database table instead of using a mock service/repository? </p>
  
  <p>Here the below code returns an empty list of object, whereas I am expecting few hundred objects. <code>findAll()</code> is a simple method for which I am trying to write JUnit but later on I will be writing JUnit for a method which takes Map as JSON from request parameters and  forms a criteria API so in this case, I would like to test </p>
  
  <blockquote>
    <ol>
    <li>Request </li>
    <li>Parsing of the request in Controller(what controller receives) </li>
    <li>And forming the SQL Criteria and returned object and that's the reason I don't want to mock service/repository. </li>
    </ol>
  </blockquote>
  
  <p>I am using Spring Boot Rest Controller and for Unit Testing, I am using Mocikito and JUnit.</p>
  
  <pre><code>@ActiveProfiles("test")
  @RunWith(SpringRunner.class)
  @WebMvcTest(CaDetailController.class)
  public class CaDetailControllerTest {
  
      private static ObjectMapper objectMapper = null;
  
      private List&lt;CaDetail&gt; caDetails;
  
      @Autowired
      private MockMvc controller;
  
      @MockBean
      CaDetailRepository repository;
  
      @BeforeClass
      public static void beforeClass() {
          objectMapper = new ObjectMapper();
  
      }
  
      @Before
      public void before() {
          caDetails = new ArrayList&lt;CaDetail&gt;();
      }
  
      @After
      public void after() {
          caDetails = new ArrayList&lt;CaDetail&gt;();
      }
  
      @AfterClass
      public static void afterClass() {
          objectMapper = null;
      }
  
      @Test
      public void getCorporateActions() throws Exception {
          MvcResult result = controller.perform(MockMvcRequestBuilders.get("/api/ca").accept(MediaType.APPLICATION_JSON)).andReturn();
          caDetails = objectMapper.readValue(result.getResponse().getContentAsByteArray(), new TypeReference&lt;List&lt;CaDetail&gt;&gt;() {
          });
          System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; caDetails : " + caDetails);
          assertNotNull(caDetails);
          assertTrue(caDetails.size() &gt; 0);
      }
  </code></pre>