gpt4 book ai didi

java - 我在模拟测试期间收到此错误 : Failed to load ApplicationContext

转载 作者:行者123 更新时间:2023-12-02 02:34:16 24 4
gpt4 key购买 nike

我在尝试运行 Controller 测试时遇到此错误

这是完整的错误:

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();

}

这是我正在尝试测试的 Controller :

    @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();
}

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

最佳答案

您的测试类应该使用@InjectMock和@Mock来模拟 Controller 和服务。

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

关于java - 我在模拟测试期间收到此错误 : Failed to load ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46632665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com