我正在尝试在Spring Boot应用程序中为Controller编写单元测试.该应用程序运行平稳,我的问题是运行其测试.
这是测试代码:
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@AutoConfigureTestEntityManager
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private MyRepository myRepository;
@Mock
ZendeskNotifier zendeskNotifier;
@Mock
ActivityLogger activityLogger;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void cannotSendFooWithoutMessageBody() throws Exception {
this.mockMvc.perform(post("/api/v1/foo/1/send"))
.andDo(print())
.andExpect(status().is4xxClientError())
.andExpect(content().string(containsString("The message body cannot be empty.")));
}
}
当我尝试运行它时,我得到:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field jobEventRepository in foo.bar.util.memsource.svc.MemsourceEventProcessor required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
这让我感到很奇怪,因为我正在提供AutoConfigureTestEntityManager批注,并且希望所有与EntityManager相关的东西都准备就绪.
解决方法:
如果Google将您带到这里,并且您正在使用Spring Boot,则可能需要将@DataJpaTest添加到测试类中.它位于org.springframework.boot:spring-boot-test-autoconfigure中.在重新运行时,您可能还会发现需要声明对org.hibernate:hibernate-validator的依赖关系.