gpt4 book ai didi

java - Spring Controller 测试依赖项失败

转载 作者:行者123 更新时间:2023-12-02 10:33:58 25 4
gpt4 key购买 nike

我有以下 Controller 类:

@Controller
public class HelloController {

private final HelloService service;

public HelloController(HelloService service) {
this.service = service;
}

@RequestMapping("/hello")
public @ResponseBody String greeting() {
return service.greet();
}

}

如您所见,它接受依赖项。这一切在服务器上运行良好。然而,在测试时,却失败了:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class WebLayerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/hello")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}

下面是 target/surefire-reports/中日志文件的输出

-------------------------------------------------------------------------------
Test set: biz.martyn.footy.WebLayerTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.278 s <<< FAILURE! - in biz.martyn.footy.WebLayerTest
shouldReturnDefaultMessage(biz.martyn.footy.WebLayerTest) Time elapsed: 0.005 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloController' defined in file [/home/martyn/eclipse-workspace/Footy/target/classes/biz/martyn/footy/controller/HelloController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'biz.martyn.footy.service.HelloService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'biz.martyn.footy.service.HelloService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

我知道 @MockBean 允许我创建依赖项的模拟,但是如果我不想模拟它呢?在这里,我很高兴真正的依赖实例能够正常使用。或者,是否因为我只测试 Web 层,所以它没有像运行完整应用程序时那样实例化 Controller ?

更新

我还尝试了@Autowired注入(inject)而不是构造函数。我的应用程序可以工作,因此依赖项被带入 Controller 中,但测试失败。以下是更新后的 Controller :

@Controller
public class HelloController {

@Autowired
private HelloService service;

@RequestMapping("/hello")
public @ResponseBody String greeting() {
return service.greet();
}

}

最佳答案

@WebMvcTest 将禁用完全自动配置,而仅应用与 MVC 测试相关的配置(即 @Controller@ControllerAdvice@JsonComponent、Converter/GenericConverter、Filter、WebMvcConfigurer 和 HandlerMethodArgumentResolver bean,但不是 @Component@Service@Repository beans,因此您必须使用 @MockBean 来满足依赖关系。

关于java - Spring Controller 测试依赖项失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436637/

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