简体   繁体   中英

Junit Testing @getmappings with h2 in memory database

I'm having issues unit testing the DbRequest controller. I have one unit test working, but I'm unable to achieve a unit test for the DBRequest controller GET mappings which does a database lookup using hibernate. I' have an H2 in memory database created for the junit tests. I've tried a variety of different setups, and nothing seems to work correctly.

Edited the below, I'm getting a NullPointer,

java.lang.NullPointerException
    at com.lmig.informaticaservice.api.DBcontroltest.saveTest(DBcontroltest.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Here is the edited test.

@RunWith(SpringRunner.class)
@SpringBootTest

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class DBcontroltest {



@Autowired
DbRequest dbRequest;


    @Autowired
    ConnectionRequestRepository connectionRequestRepository;

    private MockMvc mockMvc;
    // @Autowired
   //private TestEntityManager entityManager;



     @Test
    public void saveTest() throws Exception {
         ConnectionRequest connectionRequest = new ConnectionRequest((long) 1, "test");
         connectionRequestRepository.save(connectionRequest);


         System.out.println(connectionRequestRepository.findAll().toString());

         mockMvc.perform(get("/api/selectDB/{connectionId}" ,1))
                 .andExpect(status().isOk());


    }

}


Typical JPA repository 

    package com.test.models;

    import org.springframework.data.jpa.repository.JpaRepository;

    public interface ConnectionRequestRepository extends JpaRepository<ConnectionRequest, Long> {

    }

Here is my controller.

package com.test.api;

import com.models.ConnectionRequest;
import com.test.models.ConnectionRequestRepository;

import java.util.List;

import javax.validation.Valid;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Data
@RestController
@RequestMapping("/api/")
public class DbRequest {

    @Autowired
    private ConnectionRequestRepository connectionRequestRepository;
    private ConnectionRequest connectionRequest;

    @GetMapping("/selectDB")
    public List<ConnectionRequest> getAllRequests() {
        return connectionRequestRepository.findAll();
    }

    @GetMapping("/selectDB/{connectionId}")
    public ResponseEntity<ConnectionRequest> getRequestById(@PathVariable("connectionId") Long connectionId) throws Exception {
        ConnectionRequest connectionRequest = connectionRequestRepository.findById(connectionId)
            .orElseThrow(() -> new Exception("Connection Request " + connectionId + " not found"));
        return ResponseEntity.ok().body(connectionRequest);
    }
}

Here is the model for the database.

package com.testing.models;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Data
@Entity
@Table(name = "connrequest", schema = "testschema")
@AllArgsConstructor
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class ConnectionRequest {

    @Id
    @Column(name = "connection_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long connectionId;

    @Column(name = "requestor", nullable = false)
    private String requestor;
}

It looks like the on of the annotations on the PK of ConnectionRequest is the problem.

The annotation @GeneratedValue tells JPA that it needs to determine the value, so any provided value for the ID will be actively discarded. From the docs

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

To fix this try either removing that annotation, so then you must always provide an ID , or alternatively, after saving the entity in your test, get the ID that is assigned and call connectionRequestRepository.getOne() with that ID .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM