【问题标题】:Unable to mock Service layer in Spring MVC Controller mockito testing无法在 Spring MVC 控制器模拟测试中模拟服务层
【发布时间】:2016-08-18 03:02:45
【问题描述】:

在测试我的 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 错误。我需要正确地与该调用相交。

【问题讨论】:

  • @Autowired private 字段总是很难测试,您是否尝试过通过构造函数传递noteService
  • @ESala,刚刚尝试过 - 结果相同。
  • 试试这个:when(noteServiceMock.findById(eq(id), any(String.class))).thenReturn(note);
  • @TomVanRossom,这会导致“方法 any(Class) 对于 NoteControllerTest 类型不明确”编译错误。并且把any(String.class)改成anyString(),不会导致编译错误,但是也没有太多的方法调用,触发了真正的服务;
  • @TomVanRossom,该死的,我知道我错过了一些东西。 import static org.mockito.Mockito.*;import static org.hamcrest.Matchers.*; 这就是为什么会出现“方法 any(Class) 不明确”的原因。需要删除Matchers.*,或者像这样指定org.mockito.Mockito.any(Long.class)。我最初的问题是 - 主体对象。像 findById(anyLong(), any(Principal.class) 这样的模拟解决了我的问题,但我需要像这样 noteService.findById(id,principal); 更改控制器中的方法我想尝试的另一种方法 - 是模拟 Principal 对象。

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


【解决方案1】:

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

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

收件人:@RunWith(MockitoJUnitRunner.class)

【讨论】:

  • 我已经改变了这个。但错误的原因是,我认为我的存根方法 when() 没有拦截真正的服务调用,由于错误的模拟,我认为。
  • 如果是这种情况,那么您的 Mocked 对象不会插入到控制器中。您可以在测试用例和控制器中验证购买设置断点,并查看 NoteService 实际上是不同的。
  • 它不接受不太复杂的方法,例如when(noteServiceMock.findById(id))。我认为我需要以正确的方式模拟论点。或者问题可能是由于我使用了 Principal 对象,应该考虑到这一点。正在努力。
  • 是的,您可能还想模拟 Principal 对象。
【解决方案2】:

将 @MockBean 与 SpringJUnit4ClassRunner 一起使用。基本上控制器上下文中的对象发生了变化。当您做 MockBean 时,请注意。

@MockBean NoteService noteService;

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多