org.mockito.exceptions.base.MockitoException:使用@InjectMocks注释的字段'controller'为空

时间:2016-05-20 05:19:01

标签: java spring spring-mvc junit

  

这是我的控制器方法

@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Accept=application/json")
    public @ResponseBody ResponseMessage getUser(@RequestBody AvailableUser uuid) {
                return manager.available(uuid);
    }
  

这是我的测试控制器

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:WEB-INF/spring/appServlet/servlet-context.xml" })

public class TestController {
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    public TestController() {

    }

    @Mock
    private static Manager manager;
    @InjectMocks
    private Controller controller;
    private RMessage msg;
    private MockMvc mockMvc;
    final ObjectMapper mapper = new ObjectMapper();
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

     @Test 
     public void testgetUser() throws Exception 
     {

         AvailableUser availableUser=new AvailableUser();
         List<String> lst =new ArrayList<String>();
         lst.add("test1");
         lst.add("test2");
         availableUser.setUuId(lst);
         this.mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(availableUser)))
        .andExpect(status().isOk());
         when(manager.available(availableUser)).thenReturn(msg);
     }
    }

我在@InjectMocks控制器上出错是null。     它给了我一个暗示:

class SomeTest {
      @InjectMocks private Foo foo = new Foo();

      @Before public void setUp() {
         MockitoAnnotations.initMock(this);
}}

但我已经这样做了。

 @Before
      public void setup() {
          MockitoAnnotations.initMocks(this);
          this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
      }

我在控制台出错:

  18:16:20,004 DEBUG CacheAwareContextLoaderDelegate:93 - Storing ApplicationContext in cache under key [[MergedContextConfiguration@6483f5ae testClass = TestSurfboardController, locations = '{classpath*:WEB-INF/spring/appServlet/servlet-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
  18:16:20,106 DEBUG DirtiesContextTestExecutionListener:94 - After test method: context [DefaultTestContext@5fcd892a testClass = TestSurfboardController, testInstance = com.verizon.surfboard.TestSurfboardController@8b87145, testMethod = testgetUser@TestSurfboardController, testException = org.mockito.exceptions.base.MockitoException: Field 'surfboardController' annotated with @InjectMocks is null.
  

我正确地在控制器上应用了@InjectMock   做过MockitoAnnotations.initMocks(this);

1 个答案:

答案 0 :(得分:0)

您必须先初始化控制器。

@InjectMocks
private Controller controller = new Controller();

@InjectMocksMockMvcBuilders.standaloneSetup都不会为您执行此操作。 如果要将空值传递给它,MockMvcBuilders.standaloneSetup会抛出NPE。