通过Mockito初始化MockMvc

时间:2014-05-12 19:44:32

标签: spring spring-mvc

我在尝试让MockMvc与Mockito合作时遇到了一些麻烦。这就是我到目前为止所做的:

public class mockito {

MockMvc mockMvc;

@InjectMocks
EntryController controller;

@Mock 
DAO data_access_object;

SmokeEvent evt = new SmokeEvent(18);

@Before
public void setup() {

MockitoAnnotations.initMocks(this);
this.mockMvc = standaloneSetup(controller).setMessageConverters(new MappingJackson2HttpMessageConverter()).build(); 
//Exception thrown at above line (line 44) when the build method is called

}
@Test
public void viewRendersCorrectly() throws Exception
{
    /**
     * This test method is supposed to check to see if the controller renders
     * correctly
     */
when(data_access_object.getEvent(any(Integer.class))).thenReturn(evt);
}

}

以下是它在测试模式下抛出的堆栈跟踪。我还应该声明我已经在spring.io

上完成了Spring REST教程
java.lang.ExceptionInInitializerError: null
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1499)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1322)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:721)
at javax.servlet.GenericServlet.<clinit>(GenericServlet.java:95)
at org.springframework.test.web.servlet.MockMvcBuilderSupport.createMockMvc(MockMvcBuilderSupport.java:50)
at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.build(DefaultMockMvcBuilder.java:193)
at test.mockito.setup(mockito.java:44)

感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:0)

由于您运行的是独立测试,因此需要为EntryController方法创建standaloneSetup()的实例。实际上,您将standaloneSetup传递为空引用。

另一种选择是使用MockMvcBuilders.webAppContextSetup和适当的WebApplicationContext进行半整合测试。

例如:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes= {yourconfigurationClasses.class})
public class ... {

    @Inject 
    protected WebApplicationContext webApplicationContext;

    @Before
    public void beforeSetUp() {
      MockitoAnnotations.initMocks(this);
      mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }