我的Spring Boot应用程序启动如下:
new SpringApplicationBuilder()
.sources(ParentCtxConfig.class)
.child(ChildFirstCtxConfig.class)
.sibling(ChildSecondCtxConfig.class)
.run(args);
Run Code Online (Sandbox Code Playgroud)
配置类使用注释@SpringBootApplication.因此,我有一个根上下文和两个子Web上下文.
我想编写集成测试,我希望在那里有相同的上下文层次结构.我希望至少ChildFirstCtxConfig.class用他的父上下文(ParentCtxConfig.class)测试第一个子上下文(配置).我怎样才能做到这一点?
目前我ApplicationContext在我的测试中自动装配,所以我可以检查它.我在测试中有这个类注释:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)
但这将产生单个上下文,我想要父子层次结构.我假设我应该用@ContextHierarchy注释来注释我的测试.
将我的测试注释更改为这似乎与前面的示例完全相同:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { ParentCtxConfig.class, ChildFirstCtxConfig.class })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想介绍@ContextHierarchy并有这样的事情:
@RunWith(SpringRunner.class)
@ContextHierarchy({
@ContextConfiguration(name = "root", classes = ParentCtxConfig.class),
@ContextConfiguration(name = "child", classes = ChildFirstCtxConfig.class)
})
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)
由于在父上下文中定义的bean无法在子上下文中找到/自动装配,因此未启动上下文.设置loader = SpringBootContextLoader.class没有帮助.
示例代码:GitHub
我在这做错了什么?我的理解是Spring应该以自动装配EventRepository的方式自动装配JavaMailSender.任何指导?
mail.host='smtp.gmail.com' -
mail.port=587
mail.username=username
mail.password=password
mail.properties.mail.smtp.starttls.enable=true
Run Code Online (Sandbox Code Playgroud)
@Service
public class EventService {
private EventRepository eventRepository;
private JavaMailSender javaMailSender;
public EventService(EventRepository eventRepository, JavaMailSender javaMailSender) {
this.eventRepository = eventRepository;
this.javaMailSender = javaMailSender;
}
public Event send(Event event) {
SimpleMailMessage message = new SimpleMailMessage();
message.setText("");
message.setSubject("");
message.setTo("");
message.setFrom("");
javaMailSender.send(message);
return eventRepository.save(event);
}
}
Run Code Online (Sandbox Code Playgroud)
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationIntegrationTests {
@Autowired
private EventService eventService;
@Test
public void test() throws Exception {
eventService.save(new Event());
}
}
Run Code Online (Sandbox Code Playgroud)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No …Run Code Online (Sandbox Code Playgroud) 我的spring boot Web应用程序通过Datastax客户端使用Cassandra DB,连接如下:
public CassandraManager(@Autowired CassandraConfig cassandraConfig) {
config = cassandraConfig;
cluster = Cluster.builder()
.addContactPoint(config.getHost())
.build();
session = cluster.connect(config.getKeyspace());
}
Run Code Online (Sandbox Code Playgroud)
当我运行单元测试时,spring boot应用程序尝试加载CassandraManager Bean并连接到Cassandra DB,而不是单元测试,因为我不需要它.我收到以下错误:[localhost/127.0.0.1:9042] Cannot connect)
有没有办法避免加载这个Cassandra Manager Bean来运行我的UT,因为他们不需要连接到数据库?这样做是一种好习惯吗?
在哪种情况下我应该使用每一个?
我正在使用spring boot 1.5.8并想测试我的客户端:
@Component
public class RestClientBean implements RestClient {
private Map<String, RestTemplate> restTemplates = new HashMap<>();
@Autowired
public RestClientBean(RestTemplateBuilder builder, SomeConfig conf) {
restTemplates.put("first", builder.rootUri("first").build();
restTemplates.put("second", builder.rootUri("second").build();
}
}
Run Code Online (Sandbox Code Playgroud)
通过以下测试:
@RunWith(SpringRunner.class)
@RestClientTest(RestClient.class)
public class RestClientTest {
@Autowired
private RestClient client;
@Autowired
private MockRestServiceServer server;
@TestConfiguration
static class SomeConfigFooBarBuzz {
@Bean
public SomeConfig provideConfig() {
return new SomeConfig(); // btw. not sure why this works,
// but this is the only way
// I got rid of the "unable to …Run Code Online (Sandbox Code Playgroud) 这个方法在我所有的 JUnit 测试用例中都是空的。这个方法有什么用?
Sonarqube 抱怨
“添加嵌套注释,解释为什么此方法为空,抛出 UnsupportedOperationException 或完成实现。”
我可以通过添加一些评论来绕过这个,但我只想知道为什么有必要。
使用@DataJpaTest 时,如何配置测试类以使用处理 H2 控制台的 http 请求所需的位运行?
我正在运行使用 H2 的 Spring Boot 2.0 测试。我想在测试中设置断点并查看 H2 中表的内容。但是,当测试在断点处停止并且我将浏览器指向http://localhost:8080/h2-console 时,结果是一个空白页面,文本为“localhost 未发送任何数据”。因此,看起来要么测试运行时没有处理 H2 控制台的 http 请求所需的位,要么我使用的 URL 是错误的。
注意:当我运行测试时,控制台显示嵌入式 H2 数据库已成功启动,因此我确信 H2 确实在运行。
这是我的测试类注释:
@ExtendWith(SpringExtension.class)
@DataJpaTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
我读了一篇文章,建议在我的 pom 中包含 devtools,但这并没有解决我的问题。
编辑:我的问题的症结似乎是我无法弄清楚如何配置测试以包含嵌入式测试数据库和正在运行的 servlet。如果我同时使用@DataJpaTest和注释测试类@SpringBootTest(webEnvironment = ...),则测试会由于缺少 ServletWebServerFactory bean 而崩溃。删除@DataJpaTest修复了缺少 bean 的问题,但我不再有嵌入式测试数据库。使用 only@DataJpaTest无法启动 servlet
问题
我正在尝试运行一个简单的 spring 启动测试,但我收到的错误表明它在运行时不能 MockMvc。文档表明我使用了正确的注释,并且我使用 start.spring.io 创建了我的 pom.xml。不知道为什么它有问题。
错误:
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc'
Run Code Online (Sandbox Code Playgroud)
测试代码
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyWebApplicationTests {
@Autowired
MockMvc mockMvc;
@Test
public void Can_Do_Something() throws Exception {
mockMvc.perform(get("/hello-world")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
Run Code Online (Sandbox Code Playgroud)
文档:
我使用这个文档作为参考 - > https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-应用程序测试与模拟环境
POM文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mywebapp</groupId>
<artifactId>webapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-webapp</name>
<description>Backend application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.M1</version>
<relativePath/> <!-- …Run Code Online (Sandbox Code Playgroud) spring spring-mvc spring-boot spring-boot-test spring-webflux
我正在尝试使用构造函数注入依赖模式。
我想知道在集成测试类上注入 JPA 存储库的正确方法是什么:
我有我的源代码:
回购类
@Repository
public interface MyClassRepo extends JpaRepository<MyClass, Long> {
... methods ...
}
Run Code Online (Sandbox Code Playgroud)
构造函数注入后的服务
public class MyClassService {
private final MyClassRepo myClassRepo;
public DeviceServiceImpl(final MyClassRepo myClassRepo) {
this.myClassRepo = myClassRepo;
}
public boolean myMethodToTest() {
... whatever...
}
}
Run Code Online (Sandbox Code Playgroud)
测试一下:(这是我的问题)
SpringRunner 类选项 1:构造函数注入
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfigClass.class) // With necessary imports
@SpringBootTest
public class MyClassTester {
private final MyClassService myClassService;
private final MyClassRepository myClassRepository;
public MyClassTester (final MyClassRepository deviceRepository) {
this.myClassRepository = myClassRepository; …Run Code Online (Sandbox Code Playgroud) 我在网上查看了与测试相关的各种教程,Spring Boot并对测试的引用方式感到困惑。
有些文章将使用@WebMvcTest注释的控制器测试称为 as,Unit Test而有些则将其称为Integration Test. 不确定哪一个是正确的。
同样的问题适用于使用@DataJpaTest.
我在我的应用程序中编写了以下两个测试,一个用于控制器,另一个用于存储库。
在底部,我对两者都有一些疑问。请指导。
用户控制器测试.java
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userRepository;
@Test
public void signUp() throws Exception {
this.mockMvc.perform(get("/signup")).andExpect(status().isOk());
}
}
Run Code Online (Sandbox Code Playgroud)
UserRepositoryTest.java
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
@Test
public void whenFindByName_thenReturnEmployee() {
// given
User u = new User();
u.setName("ab");
u.setEmail("ab@cd.com");
entityManager.persistAndFlush(u);
// when
Optional<User> user = …Run Code Online (Sandbox Code Playgroud) java integration-testing unit-testing spring-boot spring-boot-test
spring-boot-test ×10
spring-boot ×7
java ×5
spring ×4
spring-test ×2
unit-testing ×2
cassandra ×1
datastax ×1
h2 ×1
jakarta-mail ×1
junit ×1
resttemplate ×1
spring-mvc ×1
testcase ×1