【问题标题】:Integration Testing Rest Controllers assertEquals fails集成测试休息控制器 assertEquals 失败
【发布时间】:2020-11-20 21:28:38
【问题描述】:

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

这是我的申请

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

【问题讨论】:

  • Hello MGallo :) 能否请您提供可以找到注解@SpringBootApplication 的类(包括包名)?
  • @FluffyDestroyerOfCode 刚刚将它添加到我的问题的顶部

标签: java spring-boot spring-mvc integration-testing


【解决方案1】:

您在类 IntegrationBookResourceImplTest 中滥用注释 @ContextConfiguration。这个Annotation是用来加载spring配置的,一般是一个带有@Configuration注解的类。您还可以在其中添加您希望 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();
    }
}

【讨论】:

  • 谢谢,我已经添加了上下文配置,否则当我运行我的测试时,我的应用程序无法启动我告诉我的应用程序上下文没有加载。我刚刚添加了一张错误的照片。见原帖末尾的png
  • 对不起,我已经更新了我的答案。查看类 BooksRestApplication。
猜你喜欢
  • 2019-02-02
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 2013-12-01
  • 1970-01-01
相关资源
最近更新 更多