Java Spring引导-使用TestRestTemplate进行测试期间类的空字段
我创建了一些REST api,并与Postman一起检查了性能-一切正常。但是,当我尝试使用TestRestTemplate测试同一端点时,除了“name”以外的所有字段都以null的形式到达控制器。有什么问题吗 我的应用程序中有两个类:ClassA和ClassB“一对多”相关。但在ClassA中,当“id”字段为空时,情况就很奇怪了。“列表”字段也为空 节课Java Spring引导-使用TestRestTemplate进行测试期间类的空字段,java,spring,testing,null,Java,Spring,Testing,Null,我创建了一些REST api,并与Postman一起检查了性能-一切正常。但是,当我尝试使用TestRestTemplate测试同一端点时,除了“name”以外的所有字段都以null的形式到达控制器。有什么问题吗 我的应用程序中有两个类:ClassA和ClassB“一对多”相关。但在ClassA中,当“id”字段为空时,情况就很奇怪了。“列表”字段也为空 节课 @Entity public class Section implements Serializable { @Id
@Entity
public class Section implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "section_id", nullable = false)
private Integer id;
@Expose
private String name;
@Expose
@JsonBackReference
@OneToMany(mappedBy = "section", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<GeologicalClass> geologicalClasses;
// Default constructor 'cause JPA
protected Section() {}
// Own constructor
public Section(String secName) {
this.name = secName;
this.geologicalClasses = new ArrayList<GeologicalClass>();
}
...
}
控制器
@RestController
public class SectionController {
@Autowired
private SectionService sectionService;
// Find all records in DB
@GetMapping("/sections")
public String findAll() {
return sectionService.findAllToJSON();
}
// Find one section by ID and return info
@GetMapping("/sections/{id}")
public String findById(@PathVariable Integer id)
throws JsonProcessingException {
return sectionService.findOneToJSON(id);
}
...
}
服务
@Service
public class SectionService {
@Autowired
private SectionRepository sectionRepository;
// Find one section by id and return info in correct form without id;
// simple method shows ArrayList as mem's address
public String findOneToJSON(Integer id) {
Section section = sectionRepository.findOne(id);
if (section == null)
throw new NotFoundException("! Section with this ID is not found !");
// With only fields with @Expose
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
return gson.toJson(section);
}
// Find each section and show it with general {}
// (uses previous function findOneToJSON)
public String findAllToJSON() {
Iterable<Section> sections = sectionRepository.findAll();
if (sections.toString().equals("[]")) {
throw new NotFoundException("! No any section found (DB is empty) !");
}
String output = "";
for (Section sec : sections) {
output += findOneToJSON(sec.getId());
}
return output;
}
...
}
并且
列出地质类别
为空。另外,如果我对“/sections/1”GET请求进行creae测试,则测试失败,因为我认为在findOne
函数中使用了id。但是“/sections”GET请求已通过,'couse。。为什么?我不习惯重新模板,但我希望在restemplate.getForEntity中为该端点请求一个数组或实体列表。除此之外,我不会在服务上转换为json,我认为这毫无意义。您通常希望在控制器中转换为json,或者更好,让jackson或其他库在您的逻辑之外处理这个问题。但您希望您的服务返回实体,这样您就可以用java本机方式与它们交互。@Eduardo Pérez,这是getForEntity所需的格式,所以我不能将其返回到节或列表中。。此外,我创建了一些其他测试(POST-req、DEL-req、special-GET(而不是CRUD)),如果我不使用ID字段,那么所有测试都通过了。那么json呢?谢谢你的建议。我刚刚开始学习spring和RESTs,这种方法对我来说似乎是最正确的。我仔细研究了您的案例,并有一些观察:1-我之前已经提到过,但您不必自己将实体转换为JSON,您可以让库(如jackson)为您这样做。在这种情况下,spring boot应该负责所有事情,因此如果您的restcontroller返回一个节,springboot将设置所有内容,以便将其转换为json:2。-在自定义转换中,我认为您在获取集合时犯了错误,因为您没有使用[]包装集合。另外,获取所有元素,然后查询每个元素是相当尴尬的,因为您正在对数据库执行N+1次查询,而不是仅执行13次。-我在第一条评论中的意思是,我认为您应该使用以下命令:ResponseEntity response=restTemplate.getForEntity(“/sections”,Section[].class);,但是,在修复前一点之前,我认为这是行不通的,因为如果不使用[]包装JSON,它就不会被检测为集合
@Service
public class SectionService {
@Autowired
private SectionRepository sectionRepository;
// Find one section by id and return info in correct form without id;
// simple method shows ArrayList as mem's address
public String findOneToJSON(Integer id) {
Section section = sectionRepository.findOne(id);
if (section == null)
throw new NotFoundException("! Section with this ID is not found !");
// With only fields with @Expose
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
return gson.toJson(section);
}
// Find each section and show it with general {}
// (uses previous function findOneToJSON)
public String findAllToJSON() {
Iterable<Section> sections = sectionRepository.findAll();
if (sections.toString().equals("[]")) {
throw new NotFoundException("! No any section found (DB is empty) !");
}
String output = "";
for (Section sec : sections) {
output += findOneToJSON(sec.getId());
}
return output;
}
...
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {SectionController.class, Application.class})
public class SectionControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private SectionRepository repository;
@Before
public void setDb() {
Section section = new Section("Section1");
GeologicalClass geo = new GeologicalClass(section, "GeoClass11", "GC11");
section.addGeoClass(geo);
repository.save(section);
}
@After
public void resetDb() {
repository.deleteAll();
}
@Test
public void whenGetSections() {
ResponseEntity<Section> response = restTemplate.getForEntity("/sections", Section.class);
assertThat(response.getStatusCode(), is(HttpStatus.OK));
assertThat(response.getBody().getName(), is("Section1"));
assertThat(response.getBody().getId(), is(1));
}
}
java.lang.AssertionError:
Expected: is <1>
but: was null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
at testing.dao.SectionControllerTest.whenCreateSection(SectionControllerTest.java:52)