问题描述
我正在尝试运行一些单元测试,并且遇到了一个我确定是由于对自动装配的误解而引起的问题.我有一个单元测试类,其中我试图在MockMvc和REST控制器上使用@Autowired
,但两者最终都为空.
I'm attempting to run some unit tests and encountering an issue that I am sure stems from a misunderstanding about autowiring. I have a unit test class in which I am trying to use @Autowired
on a MockMvc and a REST controller -- both of which end up being null.
我已经看到一些资料试图解释为什么会发生这种情况(包括更多更少的帖子和一个有用的给了我一些见识,但并没有完全帮助我解决问题).
I have seen some sources try to explain why this can happen (including this More of Less post and a helpful StackOverflow post that has given me some insight but hasn't completely helped me solve my problem).
下面是我为重现此问题而制作的示例项目中的相关源代码.
Below is relevant source code from a sample project I've made to recreate this problem.
ManagerControllerTest.java
@RunWith(SpringRunner.class)
@WebMvcTest(ManagerController.class)
public class ManagerControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private Manager manager;
@Autowired
private ManagerController controller;
@Test
public void controllerNotNull() throws Exception {
assertThat(controller).isNotNull();
}
@Test
public void testStoreSomething() throws Exception {
String path = "/manager/store-something/";
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(path)
.characterEncoding("UTF-8")
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(builder).andReturn();
assertEquals(HttpStatus.CREATED, result.getResponse().getStatus());
}
}
controllerNotNull()
测试结果
奇怪的是,当我用Java创建一个新的Gradle项目并将示例代码从这篇文章导入到其中时,controllerNotNull()
通过了.
Although, curiously, when I created a new Gradle project in Java and imported my sample code from this post into it, controllerNotNull()
passes.
然后testStoreSomething()
导致
这里有一个问题:我在误解什么?我究竟做错了什么?我可以从控制器中删除@Autowired
并仅用new ManagerController()
实例化它,但是我仍然遇到MockMvc问题.
And here in lies the question: What am I misunderstanding? What am I doing wrong? I can remove the @Autowired
from the controller and just instantiate it with new ManagerController()
but I am left with MockMvc issue.
ManagerController.java
@Controller
@RequestMapping(value = "/manager/")
public class ManagerController {
Manager manager = new Manager(new StringStorage());
@PostMapping(value = "store-something")
private ResponseEntity<?> storeSomething(String str) {
manager.storeSomething(str);
return new ResponseEntity<>(CREATED);
}
}
Manager.java
public class Manager {
private final Storage storage;
public Manager(Storage storage) {
this.storage = storage;
}
public void storeSomething(String str) {
storage.store(str);
}
}
Storage.java
public interface Storage {
void store(String str);
}
StringStorage.java
public class StringStorage implements Storage {
Map<String, String> stringMap;
@Override
public void store(String str) {
stringMap.put(str, str);
}
}
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
build.gradle 已从原始帖子中进行了编辑(以使用JUnit4),但问题仍然存在.
build.gradle Which has been edited from the original post (to use JUnit4) but the problem remains.
repositories {
jcenter()
}
apply plugin: 'java'
apply plugin: 'eclipse'
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.0.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '2.0.0.RELEASE'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.0.RELEASE'
testImplementation 'org.junit.jupiter:junit-jupiter-api:4.0.0'
testImplementation 'org.junit.jupiter:junit-jupiter-params:4.0.0'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.17.0'
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: "4.0.0"
testCompile group: 'org.junit.platform', name: 'junit-platform-launcher', version: "1.3.1"
}
推荐答案
@RestController
@RequestMapping(value = "/manager")
public class ManagerController {
@Autowired
Manager manager;
@PostMapping(value = "/store-something")
private ResponseEntity<?> storeSomething(String str) {
manager.storeSomething(str);
return new ResponseEntity<>(CREATED);
}
}
@Component
public class Manager {
@Autowired
private Storage storage;
public void storeSomething(String str) {
storage.store(str);
}
}
public interface Storage {
void store(String str);
}
@Service
public class StringStorage implements Storage {
Map<String, String> stringMap = new HashMap<>();
@Override
public void store(String str) {
stringMap.put(str, str);
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(post("/manager/store-something")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
这篇关于Spring-如何正确使用@Autowired防止控制器/MockMvc为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!