gpt4 book ai didi

java - 测试具有依赖项的 Spring Boot Controller ? (j单位)

转载 作者:行者123 更新时间:2023-12-02 01:31:50 24 4
gpt4 key购买 nike

我有这个测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(ClassToBeTested.class)
public class ClassToBeTestedTests {

@Autowired
private MockMvc mockMvc;

@Test
public void simpleTestMethodToGetClassWorking(){
Assert.assertTrue(true);
}
}

但是在我想测试的类(class)中,我有这一行:

@Autowired
AnnoyingServiceWhichIsADependency annoyingDependency;

因此,当我尝试运行测试类时 - 我收到此错误:

java.lang.IllegalStateException: Failed to load ApplicationContext

行的原因似乎引发了这个问题:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ClassToBeTested': Unsatisfied dependency expressed through field 'AnnoyingServiceWhichIsADependency'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '<package-path>.AnnoyingServiceWhichIsADependency' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我要补充一点,实际的类确实有效,并且做了它应该做的事情,但我很难让它在单元测试世界中工作。

感谢所有帮助。

最佳答案

未为依赖类创建 bean 的原因是您使用的是 @WebMvcTest 而不是 @SpringBootTest:仅扫描 Controller 和 MVC 基础结构类。来自 docs :

Can be used when a test focuses only on Spring MVC components.

由于这是一个 MVC 测试,因此您可以模拟服务依赖关系。示例:https://reflectoring.io/spring-boot-web-controller-test/

关于java - 测试具有依赖项的 Spring Boot Controller ? (j单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905780/

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