集成测试 Rest 控制器 assertEquals 失败

Integration Testing Rest Controllers assertEquals fails

我从服务器得到的响应是空白的,我不确定为什么。我已经提供了到目前为止我所完成的工作。我正在学习教程,目标只是通过将我的预期字符串与实际字符串进行比较来休息其余控制器。非常感谢您的帮助。

这是我的申请

package com.books.gallo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication()
public class BooksRestApplication {

    public static void main(String[] args) {
        SpringApplication.run(BooksRestApplication.class, args);
    }

}

这是控制器


package com.books.gallo.resource.impl;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.books.gallo.domain.Book;
import com.books.gallo.resource.Resource;
import com.books.gallo.service.BookService;


@RestController
@RequestMapping("/books")
public class BookResourceImpl implements Resource<Book> {

    @Autowired
    private BookService bookService;


    @GetMapping("/testing")
    public String test(){
        return String.format("test has run");
    }

    
    @Override
    public ResponseEntity<Collection<Book>> findAll(){
        return new ResponseEntity<>(bookService.findAll(), HttpStatus.OK);
        
    }
    
    @Override
    public ResponseEntity<Book> findById(Long id){
        return new ResponseEntity<>(bookService.findById(id), HttpStatus.OK);
        
    }
    @Override
    public ResponseEntity<Book> save(Book book){
        return new ResponseEntity<>(bookService.save(book), HttpStatus.CREATED);
        
    }
    @Override
    public ResponseEntity<Book> update(Book book){
        return new ResponseEntity<>(bookService.update(book), HttpStatus.OK);
        
    }
    @Override
    public ResponseEntity<Book> deleteById(Long id){
        return new ResponseEntity<>(bookService.deleteById(id), HttpStatus.OK);
        
    }
    

}

这是我的测试

package com.books.gallo.resource.impl;

import com.books.gallo.service.impl.BookServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(SpringExtension.class)
@WebMvcTest(BookResourceImpl.class)
@ContextConfiguration(classes = {BookServiceImpl.class})
class IntegrationBookResourceImplTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void test1() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get("/books/testing");
        MvcResult result = mvc.perform(request).andReturn();
        assertEquals("test has run", result.getResponse().getContentAsString());
    }
}

This is the error


MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /books/testing
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

org.opentest4j.AssertionFailedError: 
Expected :test has run
Actual   :

Update after removal of @ContextConfiguration(classes = {BookServiceImpl.class})

[See Error Image below][1]


  [1]: https://i.stack.imgur.com/8pKR8.png

您在 class IntegrationBookResourceImplTest 中滥用注解 @ContextConfiguration。此注解用于加载 spring 配置,通常是使用 @Configuration 注解的 class。您还可以添加希望 spring 为您管理的 bean,等等

首先,这个例子应该可行:

@ExtendWith(SpringExtension.class)
@WebMvcTest(BookResourceImpl.class)
//@ContextConfiguration(classes = {BookServiceImpl.class}) // this messes up your spring config, here you normally declare spring config classes, which are annotated with @Configuration
class IntegrationBookResourceImplTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void test1() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get("/books/testing");
        MvcResult result = mvc.perform(request).andReturn();
        assertEquals("test has run", result.getResponse().getContentAsString());
    }
}

您必须确保 spring 知道如何创建您的自定义 bean。现在您可以像这样编辑 BooksRestApplication:

@SpringBootApplication
public class BooksRestApplication {

    public static void main(String[] args) {
        SpringApplication.run(BooksRestApplication.class, args);
    }
    
    @Bean 
    public BookService bookService () {
        return new BookService();
    }
}