无法在Spring MVC Controller模拟测试中模拟服务层

时间:2016-04-24 20:15:33

标签: unit-testing spring-mvc spring-boot mockito spring-test-mvc

在测试我的NoteController时,我无法模拟我的NoteService层。运行时,会调用实际方法noteService.findById(Long id, String login)),而不是模拟方法,因此我遇到了NullPointerException。我使用Spring Boot 1.33。

这里是我的NoteController

@Controller
@RequestMapping("/notes")
public class NoteController {
    @Autowired
    private NoteService noteService;

    @ModelAttribute("noteForm")
    public NoteForm noteForm() {
        return new NoteForm();
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String editNote(@PathVariable("id") Long id, NoteForm noteForm, Principal principal) {
        Note note = noteService.findById(id, principal.getName());
        noteForm.setNote(note);
        noteForm.setAddress(note.getAddress());
        return "edit";
    }       
}

我的NoteControllerTest类

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PhonebookApplication.class)
@WebAppConfiguration
public class NoteControllerTest {

    @Mock
    NoteService noteService;
    @Mock
    View mockView;

    @InjectMocks
    NoteController controller;

    MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = standaloneSetup(controller).setSingleView(mockView).build();

    }


    @Test
    public void editNote() throws Exception {
        Long id = 1L;
        Note note = new Note();
        when(noteService.findById(id, "user")).thenReturn(note);
        mockMvc.perform(get("/notes/edit/{id}", id)).andExpect(status().isOk()).andExpect(view().name("edit"));

    }
}

异常堆栈跟踪

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at com.lardi.controller.NoteController.editNote(NoteController.java:46)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.lardi.controller.NoteControllerTest.editNote(NoteControllerTest.java:62)

PhonebookApplication - 是我的主要课程。 (NoteController.java:46)对应于我的控制线Note note = noteService.findById(id, principal.getName());我已阅读this post,但未找到解决方案。

感谢。

更新

我找到了原因。这是我的when(noteService.findById(id, "user")).thenReturn(note);存根。它不拦截控制器Note note = noteService.findById(id, principal.getName());调用。但我仍然不知道如何克服它,更改when(noteServiceMock.findById(id, any(String.class))).thenReturn(note);会导致The method any(Class<String>) is ambiguous for the type NoteControllerTest错误。我需要正确地交叉那个电话。

2 个答案:

答案 0 :(得分:0)

如果我没记错,如果您使用@Mock@InjectMocks注释,则必须使用MockitoJUnitRunner,请参阅此处的javadoc:http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/runners/MockitoJUnitRunner.html

所以改变:@RunWith(SpringJUnit4ClassRunner.class)

至:@RunWith(MockitoJUnitRunner.class)

答案 1 :(得分:0)

使用@MockBean 代替 SpringJUnit4ClassRunner。基本上控制器上下文中的对象会发生变化。当你做 MockBean 时要小心。

@MockBean NoteService noteService;