我的应用程序主类如下,其中包含一些API端点

    @CrossOrigin
//(origins = "*", maxAge = 3600)
@SpringBootApplication
@RestController
public class DemoApplication {

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



    @Autowired
//  private FormatRepository formatRepository;

      @GetMapping("/format")
    public List<Format> listFormats() {
        return formatRepository.findAll();
    }


我正在尝试为我的Controller类之一编写Junit测试用例,如下所示

@RestController
public class TypeController {
@PostMapping("/type")
public Content saveType(@RequestBody TypeDTO typeDTO) {
    return typeServiceImpl.saveType(typeDTO);
}


现在我为上述控制器定义了一个Junit测试类

@RunWith(SpringRunner.class)
@WebMvcTest(value = TypeController.class, secure = false)
public class TypeControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TypeServiceImpl typeServiceImpl;

    @MockBean
    private TypeRepository TypeRepository;

    @Test
        public void testSaveType() throws Exception {


现在,每当我运行testSaveType()

   I get the following error in the console:

        `019-08-04 13:22:41.913  WARN 25376 --- [           main] `o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DemoApplication': Unsatisfied dependency expressed through field 'formatRepository'; nested exception is` org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.foo.repository.FormatRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}`
    2019-08-04 13:22:41.919  INFO 25376 --- [           main] ConditionEvaluationReportLoggingListener :

    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-08-04 13:22:41.977 ERROR 25376 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field formatRepository in com.example.foo.DemoApplication required a bean of type 'com.example.foo.repository.FormatRepository' that could not be found.


       Action:

最佳答案

@WebMvcTest自动配置Spring MVC基础架构和限制
  扫描到@Controller@ControllerAdvice@JsonComponent
  ConverterGenericConverterFilterWebMvcConfigurer
  HandlerMethodArgumentResolver
  
  使用此批注时,不扫描常规@Component bean。


在这种情况下,您需要添加:

@MockBean
private FormatRepository formatRepository;


并存根任何所需的内容。

如果要使用此组件及其实际实现,则需要使用@SpringBootTest例如。

更新资料

理想情况下,应该在@MockBean上使用TypeServiceImpl,因此控制器的直接协作者。然后,您将不需要一起模拟存储库。

10-04 09:53