在单元测试中对Json字符串的Spring响应对象

时间:2020-11-10 17:23:37

标签: spring-boot json-deserialization spring-restcontroller

我有一个Spring Boot Rest控制器,它返回一个对象。像这样:

@RestController
@RequestMapping("books-rest")
public class SimpleBookRestController {
    
    @GetMapping("/{id}", produces = "application/json")
    public ResponseEntity<Book> getBook(@PathVariable int id) {
        return findBookById(id);
    }
 
    
}

我有一个测试此控制器方法的单元测试(mockito模拟内部的服务调用)。像这样:

@RunWith(MockitoJUnitRunner.Silent.class)
public class SimpleBookRestControllerTest {

    @Autowired
    @InjectMocks
    private SimpleBookRestController simpleBookRestController;
    @Mock
    private MyService myservice;

我现在要测试将反序列化为JSON字符串的对象对spring的作用。 在测试中,我只是测试对象,这很好。 但是我现在有一个错误,我想在单元测试中查看JSON字符串。

你会怎么做?

1 个答案:

答案 0 :(得分:1)

您不仅需要简单的单元测试-function add<KS extends Keys>( pathToArray: [...KS], value: DeepIndex<Foo, KS> extends Array<infer T> ? T : never ) { const xs = path(pathToArray, foo); if (Array.isArray(xs)) { xs.push(value); } } 不会处理到JSON的转换,因此您不能仅对其进行单元测试。

请参阅本指南:https://spring.io/guides/gs/testing-web/,或查找使用add(["bs", 0, "ds"], { e: null, f: 1 }); /* function add<["bs", 0, "ds"]>(pathToArray: ["bs", 0, "ds"], value: { e: null; f: number; }): void */ add(["bs"], {}); // Argument of type '{}' is not assignable to parameter of // type '{ c: boolean; ds: { e: null; f: number; }[]; }'. add(["a"], {}); // Argument of type '{}' is not assignable to parameter of type 'never'.(2345) add(["bs", 0, "c"], {}); // Argument of type '{}' is not assignable to parameter of type 'never'.(2345) 的示例,这是一种测试整个Web层的方法,包括REST调用及其响应。

相关问题