首页 > 解决方案 > 控制器 SpringBoot Java 的单元测试

问题描述

需要对项目的控制器部分进行单元测试,但出现错误。相信 ModelAndVIew 部分会导致问题,即使我已经嘲笑它并返回 ModelAndView 因为它是方法的返回类型。但是,它不起作用。Pom.xml 没有任何问题,因此没有添加它。项目控制器:

package com.bsptech.itcommunity.controller;

import com.bsptech.itcommunity.entity.Itproject;
import com.bsptech.itcommunity.service.inter.EmployeeProfileServiceInter;
import com.bsptech.itcommunity.service.inter.ItProjectServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(value = "/projects")
public class ProjectController {

    @Autowired
    private ItProjectServiceInter itProjectServiceInter;

    @Autowired
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @RequestMapping(method = RequestMethod.GET, path = "/{projectId}")
    public ModelAndView detail(@PathVariable("projectId") Integer projectId, ModelAndView modelAndView) {
        Itproject itproject = itProjectServiceInter.findById(projectId);
       modelAndView.addObject("itproject", itproject);
        modelAndView.setViewName("project/details");
        return modelAndView;
    }

    @GetMapping
    public ModelAndView index(ModelAndView modelAndView) {
        List<Itproject> projectList = itProjectServiceInter.findAll();
        modelAndView.addObject("projectList", projectList);
        modelAndView.setViewName("project/index");
        return modelAndView;
    }

    @RequestMapping(value = "/join", method = RequestMethod.POST)
    public String joinTeam(@RequestParam("projectId") Integer projectId){

        int result= employeeProfileServiceInter.joinProject(projectId);
        if(result==2)
            return "redirect:/projects/"+projectId+"?alreadyjoined";
        else if(result==1)
            return "redirect:/projects/"+projectId+"?joinsuccess";
        else if(result==3)
            return "redirect:/projects/"+projectId+"?alreadysent";
        else
            return "redirect:/projects?error";
    }
}

项目控制器测试

@WebMvcTest(ProjectController.class)
@SpringBootTest
public class ProjectControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private ItProjectServiceInter itProjectServiceInter;

    @MockBean
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @Mock
    ModelAndView modelAndView;

    @Test
    public void detail() throws Exception {
      OngoingStubbing resultItProject =  when(itProjectServiceInter.findById(1)).thenReturn(new Itproject(1));
        when(modelAndView.addObject(resultItProject)).thenReturn(new ModelAndView("project/details"));
        RequestBuilder request = MockMvcRequestBuilders.get("/{projectId}").accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc
                .perform(request)
                .andExpect(status().isOk())
                .andExpect(content().json("project/details"))
                .andReturn();
    }


}
Error Which I have found it: 
java.lang.NullPointerException
  at com.bsp.tech.it.community.controller.ProjectControllerTest.detail(ProjectControllerTest.java:44)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
  at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
  at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

当我使用

@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {

出现初始化错误:

java.lang.IllegalStateException:无法找到@SpringBootConfiguration,您需要在测试中使用@ContextConfiguration 或@SpringBootTest(classes=...)

在 org.springframework.util.Assert.state(Assert.java:73) 在 org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233) 在 org.springframework.boot.test.context.SpringBootTestContextBootstrapper .processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:149) 在 org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:36) 在 org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper .java:395) 在 org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312) 在 org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108) 在 org.springframework.boot 的 org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265) .test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:98) 在 org.springframework.test.context.TestContextManager.(TestContextManager.java:139) 在 org.springframework.test.context.TestContextManager.(TestContextManager.java:124 ) 在 org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:142) 在 org.springframework.test.context.junit4.SpringRunner.(SpringRunner.java:49) 在 sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 在 sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 在sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)在 org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86) 在 org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59) 在 org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass (AllDefaultPossibilitiesBuilder.java:26) 在 org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59) 在 org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33) 在 org.junit.internal.requests.FilterRequest .getRunner(FilterRequest.java:36) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) at com. intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230) 在 com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)36) 在 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) 在 com.intellij.rt.junit.JUnitStarter .prepareStreamsAndStart(JUnitStarter.java:230) 在 com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)36) 在 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49) 在 com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) 在 com.intellij.rt.junit.JUnitStarter .prepareStreamsAndStart(JUnitStarter.java:230) 在 com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

并在 pom.xml 中使用这个依赖:

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

标签: javaspring-bootunit-testingjunit

解决方案


您不需要同时使用@WebMvcTest@SpringBootTest

尝试:

@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {
...
}

推荐阅读