我是 Spring Boot 的新手,在使用 @TestPropertySource 注释和 @SpringBootTest 加载属性文件时遇到问题,这是我的代码
@RunWith(SpringRunner.class)
@SpringBootTest()
@TestPropertySource(locations="classpath:test_application.properties")
@Sql(value = {"/user_test_script.sql"})
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class UserServiceImpleIntegrationTest {
@Autowired
private UserService userService;
@Autowired
ApplicationContext applicationContext;
@Test
public void testGetAllGuestUsers() throws IOException {
List<User> users =userService.getAllGuestUsers(0, 10);
assertThat(users).isNotNull();
assertThat(users).isNotEmpty();
assertThat(users).are(new Condition<User>() {
public boolean matches(User user) {
return user.getFirstName().contains("Guest"); }
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 test_application.properties 文件内容
# Connection url for the database "test"
spring.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
# Hibernate
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true …Run Code Online (Sandbox Code Playgroud) 我有一个 jar 将包含在 spring boot 应用程序中,我正在尝试在此进行集成测试,该项目具有用于创建数据源和 JDBC 模板的配置类,我正在使用测试,
当这个jar包含在另一个项目中时,该项目中没有应用程序类,该项目可以很好地获取数据但不在同一个项目中
spring-boot-starter-test 作为依赖添加
配置
@Configuration
public class DatabaseAccesManagementConfig {
@Bean(name = "accessmngmtDataSource")
@Qualifier("accessmngmtDataSource")
@ConfigurationProperties(prefix = "accessmngmt.datasource")
public DataSource accessmngmtDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "accessmngmtJdbcTemplate")
@Qualifier("accessmngmtJdbcTemplate")
public JdbcTemplate accessmngmtJdbcTemplate(@Qualifier("accessmngmtDataSource") DataSource accessmngmtDataSource) {
return new JdbcTemplate(accessmngmtDataSource);
}
}
Run Code Online (Sandbox Code Playgroud)
道类
@Repository
public class ResourcePrivilegesDao {
static final Logger log = LoggerFactory.getLogger(ResourcePrivilegesDao.class);
@Autowired
@Qualifier("accessmngmtJdbcTemplate")
private JdbcTemplate jdbcTemplate;
public List<RP> getAll() {
log.debug("entering getAll()");
String sql = "SELECT * FROM rp";
RowMapper<RP> rowMapper = new …Run Code Online (Sandbox Code Playgroud) 我想运行我的集成测试,但我不知道如何禁用@EnableKafka.
我的应用程序看起来像这样:
@SpringBootApplication
@EnableKafka
public class MyApplication {
Run Code Online (Sandbox Code Playgroud) 我正在使用@SpringBootTest注释来运行集成测试。但它突然停止工作了!它不再加载上下文,它只是作为单元测试运行,并且所有注入的 bean 均为 null。我不记得我做了什么改变。那么,什么会导致这个问题呢?
Spring Boot 版本是 2.3。
上下文是通过添加来加载的@RunWith(SpringRunner.class)。
我有控制器的Spring Boot测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ExampleTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ExampleDAO;
@Test
public void someTest(){
exampleDAO.save(someEntity);
// call to endpoint
}
}
Run Code Online (Sandbox Code Playgroud)
我有两个数据库配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "primaryManagerFactory", basePackages = { "com.example.repository.primary" })
public class PrimaryDbConfig {
Run Code Online (Sandbox Code Playgroud)
和
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "anotherManagerFactory", basePackages = { "com.example.repository.another" })
public class AnotherDbConfig {
Run Code Online (Sandbox Code Playgroud)
测试属性片段:
spring.primary.datasource.url=jdbc:h2:mem:primary;DB_CLOSE_ON_EXIT=FALSE
spring.primary.datasource.username=sa
spring.primary.datasource.password=
spring.primary.datasource.driverClassName=org.h2.Driver
spring.another.datasource.url=jdbc:h2:mem:another;DB_CLOSE_ON_EXIT=FALSE
spring.another.datasource.username=sa
spring.another.datasource.password=
spring.another.datasource.driverClassName=org.h2.Driver
spring.jpa.properties.hibernate.show_sql=true
Run Code Online (Sandbox Code Playgroud)
GenericDAOImpl片段:
@PersistenceContext(unitName = "another-persistence-unit")
protected EntityManager entityManager;
@Override
@Transactional
public void save(T entity) …Run Code Online (Sandbox Code Playgroud) 我目前正在使用 Spring boot test 测试我的一项服务。该服务导出所有用户数据并在成功完成后生成 CSV 或 PDF。在浏览器中下载文件。
以下是我在测试类中编写的代码
MvcResult result = MockMvc.perform(post("/api/user-accounts/export").param("query","id=='123'")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_PDF_VALUE)
.content(TestUtil.convertObjectToJsonBytes(userObjectDTO)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_PDF_VALUE))
.andReturn();
String content = result.getResponse().getContentAsString(); // verify the response string.
Run Code Online (Sandbox Code Playgroud)
下面是我的资源类代码(调用到这个地方)-
@PostMapping("/user-accounts/export")
@Timed
public ResponseEntity<byte[]> exportAllUsers(@RequestParam Optional<String> query, @ApiParam Pageable pageable,
@RequestBody UserObjectDTO userObjectDTO) {
HttpHeaders headers = new HttpHeaders();
.
.
.
return new ResponseEntity<>(outputContents, headers, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
当我调试我的服务并在退出之前放置调试时,我得到的内容类型为“应用程序/pdf”,状态为 200。我试图在我的测试用例中复制相同的内容类型。不知何故,它在执行过程中总是抛出以下错误 -
java.lang.AssertionError: Status
Expected :200
Actual :406
Run Code Online (Sandbox Code Playgroud)
我想知道,我应该如何检查我的响应(ResponseEntity)。还有什么应该是响应所需的内容类型。
我想在骆驼路线下面进行测试。我在网上找到的所有示例都有以文件开头的路由,在我的情况下,我有一个 spring bean 方法,它每隔几分钟就会被调用一次,最后消息被转换并移动到 jms 和审计目录。
我对这条路线的写测试知之甚少。我目前在我的测试用例中的所有内容是
Mockito.when(tradeService.searchTransaction()).thenReturn(dataWithSingleTransaction);
from("quartz2://tsTimer?cron=0/20+*+8-18+?+*+MON,TUE,WED,THU,FRI+*")
.bean(TradeService.class)
.marshal()
.jacksonxml(true)
.to("jms:queue:out-test")
.to("file:data/test/audit")
.end();
Run Code Online (Sandbox Code Playgroud) 我想在不涉及主要 Spring 配置的情况下JUnit对我的层运行测试。DAO因此,我声明了一个用 注释的内部类,@Configuration以便它将覆盖用 注释的主应用程序类的配置@SpringBootApplication。
这是代码:
@RunWith(SpringRunner.class)
@JdbcTest
public class InterviewInformationControllerTest {
@Configuration
class TestConfiguration{
@Bean
public InterviewInformationDao getInterviewInformationDao(){
return new InterviewInformationDaoImpl();
}
}
@Autowired
private InterviewInformationDao dao;
@Test
public void testCustomer() {
List<Customer> customers = dao.getCustomers();
assertNotNull(customers);
assertTrue(customers.size() == 4);
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
Parameter 0 of constructor in com.test.home.controller.InterviewInformationControllerTest$TestConfiguration required a bean of type 'com.test.home.controller.InterviewInformationControllerTest' that could not be found.
Run Code Online (Sandbox Code Playgroud) 返回类型为空时,有什么方法可以在DAO层中为保存方法编写单元测试?我在春季启动项目中使用的是Junit Log4j。
我尝试了许多方法来断言它们。但是因为它们没有返回任何值,所以我无法断言它们。
我对 Kafka 消费者的配置位于 application.yaml 文件中。我知道如果我只有 1 个消费者,我不需要创建 ConsumerFactory bean,它会默认由 spring 设置。我需要测试我的消费者,因此我需要访问测试文件中的消费者对象,并且我不想再次配置它(我想使用 application.yaml 中的默认配置)文件来创建消费者对象。这怎么可能?
我正在尝试使用@MockBean;java 版本 11、Spring 框架版本 (5.3.8)、Spring Boot 版本 (2.5.1) 和 Junit Jupiter (5.7.2)。
@SpringBootTest
public class PostEventHandlerTest {
@MockBean
private AttachmentService attachmentService;
@Test
public void handlePostBeforeCreateTest() throws Exception {
Post post = new Post("First Post", "Post Added", null, null, "", "");
Mockito.when(attachmentService.storeFile("abc.txt", "")).thenReturn(new Attachment());
PostEventHandler postEventHandler = new PostEventHandler();
postEventHandler.handlePostBeforeCreate(post);
verify(attachmentService, times(1)).storeFile("abc.txt", "");
}
}
Run Code Online (Sandbox Code Playgroud)
@Slf4j
@Component
@Configuration
@RepositoryEventHandler
public class PostEventHandler {
@Autowired
private AttachmentService attachmentService;
@Autowired
private PostRepository postRepository;
public void handlePostBeforeCreate(Post post) throws Exception {
...
/* Here …Run Code Online (Sandbox Code Playgroud) 我正在为 Spring Boot 项目中的服务类编写单元测试。当我自动装配正在测试的类时,测试可以正确运行,而当我使用 @MockBean 而不是 @Autowire 时,测试会失败。
@SpringBootTest
class SignupServiceTest {
@Autowired SignupService signupService;
@MockBean DSService dsService;
@MockBean SignupHelper signupHelper;
@MockBean SessionHelper sessionHelper;
@MockBean CommonService commonService;
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决差异以及 @MockBean 失败的原因吗?还有一种方法可以在mockito中模拟自动装配类(当前类)的方法。
spring-boot-test ×12
java ×8
spring ×8
spring-boot ×8
junit ×3
junit5 ×2
spring-kafka ×2
spring-test ×2
apache-camel ×1
hibernate ×1
mockito ×1
testcase ×1
testng ×1