spring boot test类中,调用持久层

本文介绍了如何在Spring Boot的Test类中调用持久层。首先,需要在pom文件中添加相关测试依赖。接着,创建Test类,并使用@SpringBootTest和@RunWith注解进行配置。测试方法需标注@Test。确保Test类的根路径与启动类一致,否则可能引发找不到上下文的错误。文中提供了解决此类问题的完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom文件中添加依赖

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>

创建Test类

类上添加注解 @SpringBootTest、@RunWith

具体方法要添加 @Test 注解

根路径要与启动类相同

如果不相同,就要写                

@SpringBootTest(classes = VsecApplication.class)

如果报错,找不到上下文

@SpringBootTest(classes = VsecApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

 完整代码

@SpringBootTest(classes = VsecApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
//如果此文件所在目录跟启动类所在目录不一致就要加上classes = FirmwareApplication.class
//webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT是解决找不到spring上下文对象
public class Excel2DbTest {
    @Autowired
    private InfoMapper infoMapper;

    @Test
    public void excel2Db (){    
        infoMapper.insert(info);
        
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值