Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring boot jUnit测试失败,原因是;org.springframework.beans.factory.NoSuchBeanDefinitionException“异常”;_Java_Spring - Fatal编程技术网

Java Spring boot jUnit测试失败,原因是;org.springframework.beans.factory.NoSuchBeanDefinitionException“异常”;

Java Spring boot jUnit测试失败,原因是;org.springframework.beans.factory.NoSuchBeanDefinitionException“异常”;,java,spring,Java,Spring,我正在为Spring boot项目中的以下类编写端到端测试,但我收到org.springframework.beans.factory.NoSuchBeanDefinitionException错误,因为没有类型为'com.boot.cut_costs.service.CustomUserDetailsService'的合格bean可用 @RestController public class AuthenticationController { @Autowired prot

我正在为Spring boot项目中的以下类编写端到端测试,但我收到
org.springframework.beans.factory.NoSuchBeanDefinitionException
错误,因为
没有类型为'com.boot.cut_costs.service.CustomUserDetailsService'的合格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);
    }
}

您需要拉入配置,该配置使用测试类上的@ContextConfiguration注释对bean进行组件扫描

这可能会加载不需要的配置,甚至可能导致测试失败,因此更安全的方法是自己编写一个配置类,其中只包含运行测试所需的内容(可能只是bean的相关组件扫描)。如果您将这个配置类作为测试类的静态内部类来编写,那么只需使用@ContextConfiguration注释(不带参数)就可以拉入这个配置

@ContextConfiguration
public class MyTestClass {

   @Test
   public void myTest() {
     ...
   }

   @Configuration
   @ComponentScan("my.package")
   public static class MyTestConfig {
   }

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


如果使用
@springbootest
,还必须使用
@AutoConfigureMockMvc
来配置
MockMvc

我认为原因也在于上下文。试试这个:@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={“location/to/test config.xml”})什么是“locations”?它指向什么?请参考:您可能对本文感兴趣(第3点):以及注释
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes={AppConfig.class})
尝试将
@AutoConfigureMockMvc
@springbootest
一起使用。显然,
@WebMvcTest
只加载控制器配置。这就是为什么你会有这个DI错误(有了它,你必须为你的服务提供模拟)。这是一个spring启动应用程序,因此没有配置文件可供使用。@ArianHosseinzadeh啊,我已经更新了我的答案。您仍然可以这样做,手动强制spring启动应用程序在您的测试上下文中进行组件扫描,如下所示。我在测试类中添加了@ContextConfiguration(classes={App.class}),但它没有解决问题。我编辑了我的问题并举例说明了
App.java