Spring Test和NullPointerException

时间:2017-07-12 13:25:17

标签: java spring spring-mvc testing mockito

我必须测试一些Spring控制器。我用mockito。但是当我测试一个特定的路由时,控制器中的链接函数不能使用依赖性(NullPointerException),因为Autowired注释不起作用。

在我的代码下面:

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ClassTest {

        @InjectMocks
        private abcController abc;
        private MockMvc mockMvc;

        @Before
        public void setup() throws IOException {

            MockitoAnnotations.initMocks(this);
            this.mockMvc = MockMvcBuilders.standaloneSetup(abc).build();
        }


        @Test
        public void test1() throws Exception {
            this.mockMvc.perform(get("/api/abc/"))
                        .andExpect(status().isOk())
                        .andExpect(jsonPath("$[0]", is("a")))
                        .andExpect(jsonPath("$[1]", is("b")));
        }

Controller(这里发生NullPointer异常,databaseHandler为null):

@RestController
@ComponentScan("com.example.*")
@Repository(value="abcController")
public class abcController extends BaseController {


    @Autowired
    @Qualifier("DatabaseHandler")
    DatabaseHandlerInt databaseHandler;

    @RequestMapping(value = "/api/abc", method = RequestMethod.GET)
    public @ResponseBody ArrayList getContent() throws Exception {
        // Null pointer happend here
        return databaseHandler.example();
    }

我认为这是因为测试类缺少配置,但我找不到修复它的方法。

由于

1 个答案:

答案 0 :(得分:1)

最好的方法是在单元测试中以这种方式使用@MockBean注释,并从测试中删除mockito特定代码:

@MockBean
private DatabaseHandlerInt databaseHandler;

这样,模拟将由Spring注入,你可以使用通常的Mockito.when()样式来使用你的模拟。 查看https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html了解更多信息。