JUnit Spring Boot Appliction 中的“无法为 WebMergedContextConfiguration 加载 ApplicationContext”错误

问题描述 投票:0回答:0

Department Controller Test是Department Controller类的文本类。但是,出于某种原因,它会抛出错误:“无法为 WebMergedContextConfiguration 加载 ApplicationContext”。

DepartmentController.java

package com.kamilosinni.springbootcourse.controllers;

import com.kamilosinni.springbootcourse.entities.Department;

import com.kamilosinni.springbootcourse.errors.DepartmentNotFoundException;
import com.kamilosinni.springbootcourse.services.DepartmentServiceImpl;
import jakarta.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.logging.LogManager;


@RestController
public class DepartmentController {


    private final Logger LOGGER = LoggerFactory.getLogger(DepartmentController.class);
    @Autowired
    private DepartmentServiceImpl departmentService;

    @PostMapping("/departments")
    public Department addDepartment(@Valid @RequestBody Department department)
    {
        LOGGER.info("Department request method receiver has been called");
        return departmentService.addDepartment(department);
    }

    @GetMapping("/departments")
    public List<Department> fetchDepartmentList()
    {
        return departmentService.retAllDepartmentsList();
    }
    @GetMapping("/departments/{id}")
    public Department fetchDepartmentById(@PathVariable("id") Long departmentId) throws DepartmentNotFoundException {
        return departmentService.returnDepartmentById(departmentId);
    }

    @GetMapping("/departments/higherthanid/{id}")
    public List<Department> getDepartmentHigherThanId(@PathVariable("id") Long departmentId)
    {
        return departmentService.returnDepartmentHigherThanId(departmentId);
    }
    @GetMapping("/departments/getdepartmentbyaddress/{address}")
    public Department getDepartmentByAddress(@PathVariable("address") String address){
        return departmentService.findByDepartmentAddress(address);
    }
    @GetMapping("/departments/getdepartmentbyname/{name}")
    public Department getDepartmentByName(@PathVariable("name")String name)
    {
        LOGGER.info("Name is: " + name);
        return departmentService.findByDeparmentName(name);
    }
}

Department.java

package com.kamilosinni.springbootcourse.entities;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Department {

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Long departmentId;


    private String departmentAddress;
    private String departmentCode;
    @NotBlank(message = "Please Add Department Name")
    private String departmentName;



}


DepartmentService.java

package com.kamilosinni.springbootcourse.services;

import com.kamilosinni.springbootcourse.entities.Department;
import com.kamilosinni.springbootcourse.errors.DepartmentNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface DepartmentService {
    public Department addDepartment(Department department);
    public List<Department> retAllDepartmentsList();
    public Department returnDepartmentById(Long departmentId) throws DepartmentNotFoundException;

    public List<Department> returnDepartmentHigherThanId(Long departmentId);

    public Department findByDeparmentName(String deparmentName);

    public Department findByDepartmentAddress(String departmentAddress);

    public Department findByDepartmentNameIgnoreCase(String departmentName);

}

DepartmentServiceImpl.java

package com.kamilosinni.springbootcourse.services;

import com.kamilosinni.springbootcourse.entities.Department;
import com.kamilosinni.springbootcourse.errors.DepartmentNotFoundException;
import com.kamilosinni.springbootcourse.repositories.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;



@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentDbConnect;

    @Override
    public Department addDepartment(Department department) {
        return departmentDbConnect.save(department);
    }

    @Override
    public List<Department> retAllDepartmentsList() {
        return departmentDbConnect.findAll();
    }

    @Override
    public Department returnDepartmentById(Long departmentId) throws DepartmentNotFoundException {
        Optional<Department> department = departmentDbConnect.findById(departmentId);
        if(!department.isPresent())
        {
            throw new DepartmentNotFoundException("Department not found");
        }
        return department.get();
    }

    @Override
    public List<Department> returnDepartmentHigherThanId(Long departmentId) {
        List<Department> list = departmentDbConnect.findAll();
        List<Department> filteredList = list.stream().filter(element -> element.getDepartmentId() > departmentId).collect(Collectors.toList());
        return filteredList;
    }

    @Override
    public Department findByDeparmentName(String deparmentName) {
        return departmentDbConnect.findByDepartmentName(deparmentName);
    }

    @Override
    public Department findByDepartmentAddress(String departmentAddress) {
        return departmentDbConnect.findByDepartmentAddress(departmentAddress);
    }

    @Override
    public Department findByDepartmentNameIgnoreCase(String departmentName) {
        return departmentDbConnect.findByDepartmentNameIgnoreCase(departmentName);
    }

}

DepartmentControllerTest.java:

package com.kamilosinni.springbootcourse.controllers;

import com.kamilosinni.springbootcourse.entities.Department;
import com.kamilosinni.springbootcourse.services.DepartmentService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

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


@WebMvcTest(DepartmentController.class)
class DepartmentControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private DepartmentService departmentService;

    private Department department;

    @BeforeEach
    void setUp() {
        department = Department.builder().departmentAddress("Ahmedabad").departmentCode("IT-06").departmentName("IT").departmentId(1L).build();
    }

    @Test
    void addDepartment() throws Exception {

        Department inputDepartment = Department.builder().departmentAddress("Ahmedabad").departmentCode("IT-06").departmentName("IT").build();

        Mockito.when(departmentService.addDepartment(inputDepartment)).thenReturn(department);

        mockMvc.perform(MockMvcRequestBuilders.post("/departments").contentType(MediaType.APPLICATION_JSON).content("{\n" +
                "\t\"departmentAddress\": \"Owocna\",\n" +
                "\t\"departmentCode\": IT-06,\n" +
                "\t\"departmentName\": \"IT\"\n" +
                "}")).andExpect(MockMvcResultMatchers.status().isOk());
    }


}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kamilosinni</groupId>
    <artifactId>spring-boot-course</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-course</name>
    <description>Spring Boot course</description>
    <properties>
        <java.version>20</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>3.0.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Application.properties

server.port = 5000
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/dcbapp
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql:true

报错很明显是加载

DepartmentController
类上下文的错误,但不知道是什么原因导致的,也不知道如何解决。代码大部分是基于youtube上的一个课程,但是即使写的一样,也行不通

我尝试替换

@WebMvcTest
注释中的类 - 当我将其更改为
DeparmentControllerTest.java
(我知道这没有意义,但我想知道是什么导致了问题),测试运行没有任何问题,但由于没有控制器上下文,它当然返回 404。然而,这证实了
DepartmentController
类的上下文有问题。

java spring-boot testing javabeans applicationcontext
© www.soinside.com 2019 - 2024. All rights reserved.