【发布时间】:2018-05-17 05:13:29
【问题描述】:
我正在尝试将 Spring Boot 控制器的测试代码从 JUnit 4 转换为 JUnit 5。我几乎用 JUnit 5 替换了 JUnit 4 的所有注释,但是在尝试用 @987654322 替换 @RunWith 时遇到了一些问题@。
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = HappyPostController.class, secure = false)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class HappyPostControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private HappyPostServiceImpl happyPostService;
@InjectMocks
private HappyPostController happyPostController;
@BeforeAll
public void initialize() {
happyPostController = new HappyPostController(happyPostService);
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders
.standaloneSetup(happyPostController)
.build();
}
@Test
public void testMockCreation() {
Assertions.assertNotNull(happyPostService);
Assertions.assertNotNull(mockMvc);
}
//..... other test methods
}
错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
......
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'happyPostController' defined in file [....\HappyPostController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.rok.capp.service.HappyPostService' 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 'com.rok.capp.service.HappyPostService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
........
Test ignored.
我试图找到解决方案但失败了。请帮忙。
谢谢
【问题讨论】:
-
我认为您必须在happyPostService 字段上使用@MockBean,以便将其添加到应用程序上下文中。
-
有效!!但是为什么@Mock 在 Junit5 中却不能在 Junit4 中正常工作?
-
我必须查看您在 JUnit 4 中使用的确切代码才能回答这个问题。
标签: unit-testing spring-boot junit5