Unit testing Spring引导控制器单元测试:未能加载ApplicationContext
我有一个简单的spring引导控制器,我想为它编写单元测试,但有一个错误。我在谷歌上搜索了几个小时,但仍然找不到解决方案。以下是代码: HelloController.javaUnit testing Spring引导控制器单元测试:未能加载ApplicationContext,unit-testing,spring-boot,Unit Testing,Spring Boot,我有一个简单的spring引导控制器,我想为它编写单元测试,但有一个错误。我在谷歌上搜索了几个小时,但仍然找不到解决方案。以下是代码: HelloController.java @RestController public class HelloController { @Autowired private HelloService helloService; @GetMapping("/hello") public String sayHello(){
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String sayHello(){
return helloService.sayHello();
}
}
HelloService.java:
@Service
public class HelloService {
public String sayHello(){
return "Hello";
}
}
和单元测试文件:
HelloControllerTest.java:
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private HelloService helloService;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void sayHello() throws Exception {
when(helloService.sayHello()).thenReturn("thach");
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("thach"));
}
}
但有一个错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with @ContextConfiguration or @ContextHierarchy.
at org.springframework.util.Assert.notNull(Assert.java:134)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:57)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 24 more
有人能帮我吗?我只是Spring boot的新手我也有类似的问题。请参阅下面的代码:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
ApplicationService applicationService;
@Test
public void testGetImagePath() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/application/get-image")
.contentType(MediaType.IMAGE_GIF);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println(result.getResponse());
}
请参见下面的测试用例执行:
检查您使用的注释,即:
1) @RunWith(SpringRunner.class)
2) @SpringBootTest
3) @AutoConfigureMockMvc我也有类似的问题。请参阅下面的代码:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
ApplicationService applicationService;
@Test
public void testGetImagePath() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/application/get-image")
.contentType(MediaType.IMAGE_GIF);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println(result.getResponse());
}
请参见下面的测试用例执行:
检查您使用的注释,即:
1) @RunWith(SpringRunner.class)
2) @SpringBootTest
3) @AutoConfigureMockMvc这里缺少的是
@springbootest
注释。此注释用于加载@Configuration
类进行测试,并使用默认端口启动嵌入式容器。
如果未指定
@Configuration
类,它将使用默认的@springbootplication
类,因为它的注释中包含@Configuration
。这里缺少的是@springbootest
注释。此注释用于加载@Configuration
类进行测试,并使用默认端口启动嵌入式容器。
如果未指定
@Configuration
类,它将使用默认的@springbootplication
类,因为它的注释中包含@Configuration
。对于遇到相同问题的任何人来说,使用@MockBean非常重要。(@Mock不会剪断它)
见:
我们使用@MockBean为GreetingService创建并注入一个mock(如果不这样做,应用程序上下文将无法启动),并使用Mockito设置其期望值
所以,如果OP被替换的话,一切可能都会好起来
@Mock
私人HelloService HelloService;
与
@MockBean
私人HelloService HelloService;
因此,对于遇到相同问题的任何人来说,接受答案中的附加类注释应该是不必要的,使用@MockBean是很重要的。(@Mock不会剪断它) 见: 我们使用@MockBean为GreetingService创建并注入一个mock(如果不这样做,应用程序上下文将无法启动),并使用Mockito设置其期望值 所以,如果OP被替换的话,一切可能都会好起来
@Mock
私人HelloService HelloService;
与
@MockBean
私人HelloService HelloService;
因此,如果转换为@SpringBootTest,则不需要接受答案中的附加类注释,它将成为集成测试。但是我们只想用@WebMvcTest测试特定的控制器(单元测试),这样它将如何成为一个可行的解决方案。如果转换为@SpringBootTest,它将成为集成测试。但是我们只想用@WebMvcTest测试特定的控制器(单元测试),这样它将如何成为一个可行的解决方案。我遇到了同样的问题,并尝试了不同的方法,但没有一种方法不起作用,最后,我在测试类中添加了两个注释来解决我的问题:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
HelloControllerTest {
}
如果不想生成随机端口来测试API,只需添加以下注释:
@SpringBootTest
@AutoConfigureMockMvc
HelloControllerTest {
}
我遇到了相同的问题,尝试了不同的方法,但没有一种方法不起作用。最后,我在测试类中添加了两个注释,解决了我的问题:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
HelloControllerTest {
}
如果不想生成随机端口来测试API,只需添加以下注释:
@SpringBootTest
@AutoConfigureMockMvc
HelloControllerTest {
}
可能重复的可能重复的某些情况需要为@SpringBootTest注释指定classes属性某些情况需要为@SpringBootTest注释指定classes属性