我在模拟测试期间遇到此错误:无法加载ApplicationContext

时间:2017-10-08 15:14:14

标签: java spring unit-testing spring-test

我在尝试运行控制器测试时遇到此错误

这是完整的错误:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookController':
 Unsatisfied dependency expressed through field
 'bookService'; nested exception is  

这是测试:

@Test
public void bookRemoveTest() throws Exception {
    securityService.autologin("admin", "admin");

    Book book = new Book();
    book.setId(1L);
    bookService.findOne(1L);

    expect(bookService.findOne(anyLong())).andReturn(book);
    replay(bookService);
    MvcResult result = mockMvc
            .perform(post("/book/remove")
                    .accept(MediaType.TEXT_HTML)
                    .contentType(MediaType.TEXT_HTML))


            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.TEXT_HTML))
            .andReturn();

}

这是我试图测试的控制器:

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
        public String remove(
                @ModelAttribute( "id" ) String id, Model model
        ) {
            bookService.removeOne(Long.parseLong(id.substring(8)));
            List<Book> bookList = bookService.findAll();
            model.addAttribute("bookList", bookList);

            return "redirect:/book/bookList";
        }

我个人认为问题来自这里:

     @Before
     public void setUp() {
            bookService = createMock(BookService.class);

            ReflectionTestUtils.setField(bookController, "bookService", bookService);

            userRepository= createMock(UserRepository.class);
            ReflectionTestUtils.setField(bookController, "userRepository", userRepository);

            mockMvc = standaloneSetup(bookController)
                    .setMessageConverters(new ByteArrayHttpMessageConverter())
                    .build();
        }

在这里,我尝试执行模拟注入,以便在模拟测试中使用我的服务

1 个答案:

答案 0 :(得分:2)

您的测试类应使用@InjectMock和@Mock来模拟控制器和服务。

public class BookControllerTest {

    @InjectMocks
    BookController controller;

    @Mock
    BookService bookService;  // will be inject to BookController

    MockMvc mockMvc;

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

    @Test
    public void bookRemoveTest() throws Exception {
        ...
    }
}

更多详情:PROPERLY TESTING SPRING MVC CONTROLLERS