java - Spring boot jUnit 测试失败,因为 "org.springframework.beans.factory.NoSuchBeanDefinitionException"

标签 java spring

我正在为 Spring boot 项目中的以下类编写端到端测试,但收到 org.springframework.beans.factory.NoSuchBeanDefinitionException 错误,因为 No Qualifying类型为“com.boot.cut_costs.service.CustomUserDetailsS​​ervice”的 bean 可用

@RestController
public class AuthenticationController {

    @Autowired
    protected AuthenticationManager authenticationManager;
    @Autowired
    private CustomUserDetailsService userDetailsServices;
    @Autowired
    private UserDetailsDtoValidator createUserDetailsDtoValidator;

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public void create(@RequestBody UserDetailsDto userDetailsDTO, HttpServletResponse response, BindingResult result) {
        // ...
        userDetailsServices.saveIfNotExists(username, password, name);
        // ...
        if (authenticatedUser != null) {
            AuthenticationService.addAuthentication(response, authenticatedUser.getName());
            SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
        } else {
            throw new BadCredentialsException("Bad credentials provided");
        }
    }
}

测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(AuthenticationController.class)
public class AuthenticationControllerFTest {

    @Autowired 
    private MockMvc mockMvc;

    @MockBean
    private AuthenticationManager authenticationManager;

    @Test
    public void testCreate() throws Exception {
        Authentication authentication = Mockito.mock(Authentication.class);
        Mockito.when(authentication.getName()).thenReturn("DUMMY_USERNAME");
        Mockito.when(
                authenticationManager.authenticate(Mockito
                    .any(UsernamePasswordAuthenticationToken.class)))
                .thenReturn(authentication);

        //....
        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post("/signup")
            .accept(MediaType.APPLICATION_JSON).content(exampleUserInfo)
                .contentType(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        MockHttpServletResponse response = result.getResponse();
    }
}

我认为发生此错误是因为在测试环境中,spring 上下文的加载方式与开发/生产环境中的加载方式不同。我应该如何解决这个问题?

编辑 1

我的 Spring boot 应用程序入口点是 App.java:

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

最佳答案

@WebMvcTest 仅加载 Controller 配置。这就是为什么你有这个 DI 错误(有了它,你必须为你的服务提供模拟)。因此,如果您需要注入(inject)服务,可以使用@SpringBootTest

如果您使用@SpringBootTest,则还必须使用@AutoConfigureMockMvc来配置MockMvc

关于java - Spring boot jUnit 测试失败,因为 "org.springframework.beans.factory.NoSuchBeanDefinitionException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184882/

相关文章:

Java 虚函数调用

java - http.nonProxyHosts 仅在本地主机上被忽略

java - 读取非文本内容并将其写回文件

java - 取消部署 mule 应用程序时如何停止 java 类

java - Spring Security 超时时将用户重定向到登录页面

java - BigDecimal 的加法

java - AspectJ 和 Spring : Exclude @After method execution when method throws an exception

java - 在类型 'contextMessage' 的对象上找不到字段或属性 'org.springframework.webflow.engine.impl.RequestControlContextImpl'

java - Maven - 无法执行目标 org.springframework.boot :spring-boot-maven-plugin:2. 4.1:run

java - 将 Objective-c 的枚举转换为 Android 的枚举