通过模拟服务进行弹簧控制器测试



更喜欢使用模拟和单元测试助手进行春季测试:

模拟服务替换多个依赖项

在此处输入图像描述

@Controller
@RequestMapping("/people")
public class PeopleController {
    @Autowired
    protected PersonService personService;
    @GetMapping
    public ModelAndView people(Model model) {
        for (Person person: personService.getAllPeople()) {
            model.addAttribute(person.getName(), person.getAge());
        }
        return new ModelAndView("people.jsp", model.asMap());
    }
}

私人模拟Mvc mockMvc:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PeopleControllerTest {
    @Autowired
    PersonService personService;
    private MockMvc mockMvc;
    @Configuration
    static class Config {
        // Other beans
        @Bean
        public PersonService getPersonService() {
            return mock(PersonService.class);
        }
    }
    @Test
    public void testPeople() throws Exception {
        // When
        ResultActions actions = mockMvc.perform(get("/people"));
    }
}

我想跑mockMvc时出现错误

java.lang.NullPointerException

执行以下步骤:

  1. 创建服务模拟而不是原始服务("PersonServiceMock")

  2. 将服务替换为服务模拟

        @Autowired
        PersonService personService;
        @Autowired
        PeopleController peopleController;
        private MockMvc mockMvc;
        @Before
        public void setup() {
        peopleController = new PeopleController(new personServiceMock());
        mvc = MockMvcBuilders.standaloneSetup(peopleController).build();
       }    
        @Configuration
        static class Config {
            // Other beans
            @Bean
            public PersonService getPersonService() {
                return mock(PersonService.class);
            }
        }
        @Test
        public void testPeople() throws Exception {
            // When
            ResultActions actions = mockMvc.perform(get("/people"));
        }
    }
    

那是因为您从未在代码中初始化mockMvc,并且您访问它的位置会导致nullPointerException。您需要在使用它之前对其进行初始化,并且由于类中的多个测试可能会使用它,因此最好的地方是setup()@before 注释的方法。请尝试以下操作:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PeopleControllerTest {
@Autowired
PersonService personService;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
  mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

@Configuration
static class Config {
    // Other beans
    @Bean
    public PersonService getPersonService() {
        return mock(PersonService.class);
    }
}
@Test
public void testPeople() throws Exception {
    // When
    ResultActions actions = mockMvc.perform(get("/people"));
}
}

从源代码中我看到 mockMvc 没有任何值,这就是为什么它为这行代码命中"java.lang.NullPointerException":

ResultActions actions = mockMvc.perform(get("/people"));

要让它运行,我认为首先需要给 mockMvc 赋予价值。
按构造函数:

@Test
public void testPeople() throws Exception {
    mockMvc = new MockMvc();
    // When
    ResultActions actions = mockMvc.perform(get("/people"));
}

或自动连线 :

@Autowired
MockMvc mockMvc

取决于模拟Mvc类的目的

相关内容

  • 没有找到相关文章

最新更新