Необходимо выполнить модульное тестирование для части контроллера проекта, но есть ошибка. Поверьте, часть ModelAndVIew является причиной проблемы, даже если я ее высмеял и возвратил ModelAndView, так как это тип возвращаемого метода. Однако это не работает. Нет проблем с Pom. xml, поэтому не добавил его. ProjectController:
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";
}
}
ProjectControllerTest
@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. boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration (SpringBootTestContextBootstrapper java:. 149) при org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration (. WebMvcTestContextBootstrapper * +1032 *: 36) при org.springframework. test.context.support.AbstractTestContextBootstrapper.buildMergedContextCo nfiguration (AbstractTestContextBootstrapper java:. 395) в org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration (AbstractTestContextBootstrapper java:. 312) в org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration (AbstractTestContextBootstrapper. java: 265. 98) в org.springframework.test.context.TestContextManager. (TestContextManager. java: 139) в org.springframework.test.context.TestContextManager. (TestContextManager. java: 124) в org.springframe. .junit4.SpringJUnit4ClassRunner.createTestContextManager (SpringJUnit4ClassRunner. java: 151) в org.springframework.test.context.junit4.SpringJUnit4Cl assRunner. (SpringJUnit4ClassRunner. java: 142) в org.springframework.test.context.junit4.SpringRunner. (SpringRunner. java: 49) в sun.reflect.NativeConstructorAccessorImpl.newInstance0 (родной метод) в исходном методе (родной метод) NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl. java: 62) в sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl. java: 45) в java .lang.refn. в org.junit.internal.builders.AnnotatedBuilder.buildRunner (AnnotatedBuilder. java: 104) в org.junit.internal.builders.AnnotatedBuilder.runnerForClass (AnnotatedBuilder. java: 86un.unit) или .RunnerBuilder.safeRunnerForClass (RunnerBuilder. java: 59) по адресу org.junit.internal.builders.AllDefaultPossabilitiesBuilder.runnerForClass (AllDefaultPossabilitiesBuilder. java: 26) по адресу org.junitilBunderBunderunun 1051 *: 59) в org.junit.internal.requests.ClassRequest.getRunner (C lassRequest. java: 33) по адресу org.junit.internal.requests.FilterRequest.getRunner (FilterRequest. java: 36) по адресу com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs (JUnit4Iunte * 490 * at). .intellij.rt.junit.IdeaTestRunner $ Repeater.startRunnerWithArgs (IdeaTestRunner. java: 33) в com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart (JUnitStarter. * 1056.jt. 230) .JUnitStarter.main (JUnitStarter. java: 58)
И в пом. xml Используя эту зависимость:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>