Spring boot 3 Junit 5集成测试错误创建名称错误的bean



通过运行单元测试,我已经验证了CandidateRepository工作正确。然而,当我尝试为CandidateController运行集成测试时,我总是得到一个错误,说"没有'CandidateRepository'类型的合格bean可用"。我不确定为什么会发生这种情况,因为我已经在代码中包含了必要的注释(@Repository、@Service和@RestController)和组件扫描。对如何解决这个问题有什么想法吗?

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'candidateController' defined in file [D:java_reposmicro-librarymachine_learning_javatalent-sourcing-systembuildclassesjavamaincomtsstalentsourcingsystemapplicationcandidatecontrollerCandidateController.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'candidateServiceImpl' defined in file [D:java_reposmicro-librarymachine_learning_javatalent-sourcing-systembuildclassesjavamaincomtsstalentsourcingsystemapplicationcandidateserviceimplCandidateServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'com.tss.talentsourcingsystem.application.candidate.repository.CandidateRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

下面是我的集成测试代码:

@ExtendWith(MockitoExtension.class)
@SpringBootTest
@Transactional
class CandidateControllerIntegrationTest {
private static final String BASE_URL = "http://localhost:8081/api/v1/candidates";
private MockMvc mockMvc;
private ObjectMapper objectMapper;
@Autowired
private WebApplicationContext context;
@Autowired
private CandidateRepository candidateRepository;
@Autowired
private CandidateService candidateService;
@Autowired
private CandidateController candidateController;
@BeforeEach
void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
this.objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
}
// tests here
}

如何解决此错误并使集成测试通过?我已经试过了MockBean

确保将@Service和@Transactional放在CandidateServiceImpl类之上。

最新更新