在Spring Boot中进行完全验证测试时,如果遇到注入失败的问题,通常是由于以下几个原因导致的:
@Autowired
或构造函数注入。@SpringBootTest
、@RunWith(SpringRunner.class)
(或@ExtendWith(SpringExtension.class)
如果你使用的是JUnit 5)。下面是一个示例,展示了如何进行完全验证测试并解决注入失败的问题:
假设我们有一个简单的Spring Boot应用程序,包含一个服务类和一个控制器类:
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
// src/main/java/com/example/demo/service/MyService.java
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String sayHello() {
return "Hello, World!";
}
}
// src/main/java/com/example/demo/controller/MyController.java
package com.example.demo.controller;
import com.example.demo.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final MyService myService;
@Autowired
public MyController(MyService myService) {
this.myService = myService;
}
@GetMapping("/hello")
public String sayHello() {
return myService.sayHello();
}
}
// src/test/java/com/example/demo/DemoApplicationTests.java
package com.example.demo;
import com.example.demo.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private MyService myService;
@Test
public void contextLoads() {
assertThat(myService).isNotNull();
}
@Test
public void testSayHello() {
String result = myService.sayHello();
assertThat(result).isEqualTo("Hello, World!");
}
}
DemoApplicationTests
应该放在com.example.demo
包或其子包中,以确保Spring Boot能够扫描到它。@SpringBootTest
注解来加载完整的Spring上下文。@RunWith
注解,因为@SpringBootTest
已经包含了必要的配置。MyService
类上有@Service
注解,这样Spring Boot才能将其识别为一个Bean。领取专属 10元无门槛券
手把手带您无忧上云