使用Mockito测试用例错误400获取NullPointerEXception

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

我正在使用发帖请求添加3个类别,并且对于每个类别,将3个相应的课程添加到同一课程。最后,我需要获取一个包含课程列表的Categories数组。但是,在使用Mockito执行测试驱动开发时,我会收到状态代码为400的null Pointer Exception。请同样帮助我。

Test.java

@RunWith(value = MockitoJUnitRunner.class)
@WebMvcTest(Controller.class)
class Test {

    @Autowired
    MockMvc mvc;

    @MockBean
    service s;

    @MockBean
    Controller cont;

    @MockBean
    StatusResultMatchers sr;

    @org.junit.jupiter.api.Test
    void catTest() throws Exception {
        Course c1=new Course(1,"Technology",100,50,7415);
        Course c2=new Course(2,"Technology",100,50,7415);
        Course c3=new Course(3,"Technology",100,50,7415);
        Course[] c= {c1,c2,c3};
        List<Course> cl=new ArrayList<Course>();
        cl.add(c1);
        cl.add(c2);
        cl.add(c3); 
        Category ca=new Category(7415,"java","very gud", cl);

        when(s.getAllContents()).thenReturn(cl);
        mvc.perform(get("/getcourse")).andExpect(sr.is2xxSuccessful()).andReturn();
    }

}

Controller.java

@RestController
public class Controller {

      @Autowired
      private service cs;


      @RequestMapping(value="/addcat", method=RequestMethod.POST)
      public void addcat(@RequestBody Category[] categ) throws Exception{
          for(int i=0;i<3;i++)
            cs.cat[i]=categ[i];  
      }

    @RequestMapping(value="/addcour", method=RequestMethod.POST)
      public void addcour(@RequestBody Course[] cour) {
        for(Category c:cs.cat) {
            cs.co=null;
            for(int i=0;i<3;i++) {
                if(cour[i].getCategoryId()==c.getCategoryId()) {
                    cs.co.add(cour[i]);
                    c.setCourseList(cs.co);
                }
            }
        }
    }

    @RequestMapping(value="/getcat", method=RequestMethod.GET)
      public @ResponseBody Category[] getcat(){
        return cs.getAllCategories();
     }

    @RequestMapping(value="/getcourse", method=RequestMethod.GET)
      public @ResponseBody List<Course> getcourse(@RequestBody Map<Category,List<Course> > cour){
        return cs.getAllContents();
     }

}

Service.java

@Service
public class service {

    public List<Course> co=new ArrayList<Course>();
    public  Category[] cat=new Category[3];
    public List<Course>  getAllContents() {
        return co;
    }
    public Category[] getAllCategories() {
        return cat;
    }
}

测试输出

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /getcourse
       Parameters = {}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.example.demo.controller.Controller$MockitoMock$138133307
           Method = com.example.demo.controller.Controller$MockitoMock$138133307#getcourse(Map)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2020-06-03 17:38:59.573  INFO 26360 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

我已更新代码。现在,不存在NullPOinterException。但是我得到一个空列表“ ActualCourse”。请在下面找到d代码:

Test.java

@RunWith(value = MockitoJUnitRunner.class)

@ WebMvcTest(Controller.class)类测试{

@Autowired
MockMvc mvc;

@MockBean
service testService;

@MockBean
Controller targetController;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@org.junit.jupiter.api.Test
void catTest() throws Exception  {
    // Mock Data
    Course c1=new Course(1,"Technology",100,50,7415);
    Course c2=new Course(2,"Technology",100,50,7415);
    Course c3=new Course(3,"Technology",100,50,7415);

    List<Course> expectedCourse=new ArrayList<Course>();
    expectedCourse.add(c1);
    expectedCourse.add(c2);
    expectedCourse.add(c3); 

    Category expectedCategory=new Category(7415,"java","very gud", expectedCourse);

    when(testService.addcour()).thenReturn(expectedCourse);     
    List<Course> actualCourse = targetController.addcour();     
    assertEquals(expectedCourse,actualCourse);
}

Controller.java

@RestController
public class Controller {

  @Autowired
  private service cs;


  @RequestMapping(value="/addcat", method=RequestMethod.POST)
  public List<Category> addcat(@RequestBody Category[] categ) throws Exception{
      return cs.addcat(categ);
  }

@RequestMapping(value="/addcour", method=RequestMethod.POST)
  public List<Course> addcour() {
    return cs.addcour();
}

@RequestMapping(value="/getcat", method=RequestMethod.GET)
  public @ResponseBody List<Category> getcat(){
    return cs.getAllCategories();
 }

@RequestMapping(value="/getcourse", method=RequestMethod.GET)
  public @ResponseBody List<Course> getcourse(){
    return cs.getAllCourses();
 }
 }

Service.java

@Service
public class service {

public List<Category> cat=new ArrayList<Category>();
public List<Course> c=new ArrayList<Course>();

List<Course> empty=new ArrayList<Course>();
List<Category> category=new ArrayList<Category>();

public List<Category> addcat(Category[] categ) {
    int flagcat=0,flagcourse=0;

    Category c1=new Category(7415,"Technology","Java",empty);
    Category c2=new Category(2,"Technology","Java",empty);
    Category c3=new Category(7314,"Technology","Java",empty);

    Category c4=new Category(4,"Technology","Java",empty);
    Category c5=new Category(8415,"Technology","Java",empty);
    Category c6=new Category(6,"Technology","Java",empty);

    category=Arrays.asList(c1,c2,c3,c4,c5,c6);
    Iterator icat=category.iterator();
    Iterator icourse=c.iterator();

    Object ncourse=new Object();
    Object ncat=new Object();

    while(icat.hasNext()) {
        List<Course> co=new ArrayList<Course>();

        flagcat++;
        flagcourse=0;

        ncat=icat.next();

        while(icourse.hasNext()) {
            ncourse=icourse.next();

            if(((Category) ncourse).getCategoryId()==((Category) ncat).getCategoryId()) {
                flagcourse++;
                co.add((Course) ncourse);
                if(flagcourse==3) {
                    ((Category) ncat).setCourseList(co);
                    break;
                }
            }
        }
        cat.add((Category) icat);
        if(flagcat==3) {
            break;
        }
    }
    return cat;

}

public List<Course> addcour() {
    Course c1=new Course(1,"Technology",100,50,7415);
    Course c2=new Course(2,"Technology",100,50,7415);
    Course c3=new Course(3,"Technology",100,50,7415);

    Course c4=new Course(4,"Technology",100,50,7314);
    Course c5=new Course(5,"Technology",100,50,7314);
    Course c6=new Course(6,"Technology",100,50,7314);   

    Course c7=new Course(7,"Technology",100,50,8415);
    Course c8=new Course(8,"Technology",100,50,8415);
    Course c9=new Course(9,"Technology",100,50,8415);
    Course c10=new Course(10,"Technology",100,50,8415);

    List<Course> c=Arrays.asList(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10);
    return c;
}

public List<Course> getAllCourses() {

    return c;
}
public List<Category> getAllCategories() {
    return cat;
}
}

输出

org.opentest4j.AssertionFailedError: expected: <[com.example.demo.Course@6ecc02bb, com.example.demo.Course@31973858, com.example.demo.Course@65514add]> but was: <[]>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.example.demo.test.Test.catTest(Test.java:75)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
spring-mvc mockito tdd
1个回答
0
投票

似乎您的代码中存在一些设计问题。在您的控制器中,getcourse方法正在接收请求正文Map<Category,List<Course> > cour,但是HTTP方法是GET,因此不应使用GET方法发送数据(有关更多上下文,请检查this answerthis )。

另一方面,您的getcourse未使用cour参数,因此将此方法重构为:

@RequestMapping(value="/getcourse", method=RequestMethod.GET)
public @ResponseBody List<Course> getcourse(){
        return cs.getAllContents();
}

让我知道它是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.