gpt4 book ai didi

java - Spring MVC 测试失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:18:07 26 4
gpt4 key购买 nike

我正在尝试运行 Spring MVC 测试,但一直收到此异常。

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 java.lang.NullPointerException

异常发生是因为 Autowiring 的依赖,

    @Autowired
private AccountService accountService;

未在测试中注入(inject)(在测试外工作正常)。

谁能帮我解决这个问题。这是我的代码:

//AccountControllerITTest类

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class AccountControllerITest {

private MockMvc mvc;

ObjectMapper om;

@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}

@Test
public void getAccounts() throws Exception {
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get("/api/accounts"))
.andExpect(status().isOk())
.andReturn();
}
}

//账户 Controller

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

@Autowired
private AccountService accountService;

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Set<AccountInfo>> getAccounts(@RequestParam(value = "firstName", required = false) String firstName,
@RequestParam(value = "surName", required = false) String surName) {
Set<AccountInfo> accounts = accountService.getAccounts(firstName, surName);
return new ResponseEntity<>(accounts, HttpStatus.OK);
}

感谢您的帮助!

最佳答案

因为您使用的是独立设置:mvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();。如果您通过 new AccountController() 创建 Controller ,Spring 没有机会注入(inject) accountService,因为它不控制实例创建和连接。

你有两个选择:

  1. 将您的测试切换为单元测试,并且不要使用 SpringJUnit4ClassRunnerMockServletContext全部。您可以使用 @InjectMocks 注入(inject)私有(private) accountService:

    public class AccountControllerITest {

    private MockMvc mvc;

    ObjectMapper om;

    @Mock
    private AccountController accountController = new AccountController();

    @InjectMocks
    private AccountService accountService = new Mockito.mock(AccountService.class);

    @Before
    public void setUp() throws Exception {
    mvc = MockMvcBuilders.standaloneSetup(accountController).build();
    }

    您还可以将增强功能应用于您的 Controller 。将字段注入(inject)替换为构造函数注入(inject),您可以在测试中通过构造函数将 accountService 传递给 Controller ​​。这样你就不需要使用 @InjectMocks 了。

  2. 使用 webAppContext 设置:

    @Autowired
    private WebApplicationContext webApplicationContext;

    @BeforeMethod
    public void init() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

关于java - Spring MVC 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32348270/

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