gpt4 book ai didi

java - @SpringBootTest 使用测试属性(测试数据库)文件运行

转载 作者:行者123 更新时间:2023-11-28 21:17:08 26 4
gpt4 key购买 nike

我有一个关于“spring boot 2”的项目,我想测试一下。表:

@Entity
@Table(name = "Contract")
public class Contract extends ADBObjectWithID<ContractBean>
{
@NotBlank
@Size(max = 512)
private String name;

@Size(max = 2056)
private String comment;

@Override
public ContractBean toBean()
{
return new ContractBean(getId(), getName(), getComment());
}
}

存储库是 CrudRepository<Contract, Long> :

服务:

@Service
public class ContractServiceImpl implements ContractService
{
private ContractRepository contractRepository;

public ContractServiceImpl(ContractRepository contractRepository)
{
this.contractRepository = contractRepository;
}

@Override
@Transactional
public Contract saveObject(ContractBean contractBean)
{
Contract contract;
if (contractBean.getId() == null)
{
contract = new Contract();
}
else
{
contract = findById(contractBean.getId()).orElseThrow(() -> new NullPointerException("Contract not found"));
}
contract.setName(contractBean.getName());
contract.setComment(contractBean.getComment());
return contractRepository.save(contract);
}

@Override
@Transactional
public void deleteObject(ContractBean contractBean)
{

}

@Override
public Optional<Contract> findById(Long id)
{
return contractRepository.findById(id);
}
}

我想测试“服务”层并在测试数据库中测试它。 “application-test.properties”中提供了测试数据库的参数,但我运行测试时,“SpringBoot”使用了“application.properties”中的真实数据库。
测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ContractTest
{
@Autowired
private ContractService contractService;

@Test
public void createContract()
{
String name = "Contract name";
String comment = "Contract comment";

ContractBean contractBean = new ContractBean();
contractBean.setName(name);
contractBean.setComment(comment);

Contract contract = contractService.saveObject(contractBean);
Assert.assertEquals(name, contract.getName());
Assert.assertEquals(comment, contract.getComment());

contractBean = contract.toBean();
Assert.assertEquals(name, contractBean.getName());
Assert.assertEquals(comment, contractBean.getComment());
}
}

请问,如何切换到测试基地?我在尝试 @PropertySource("classpath:application-test.properties")@TestPropertySource("classpath:application-test.properties") , 但不起作用

最佳答案

使用 Spring Profile 测试运行。

-Dspring.profiles.active=测试

您可以将默认配置文件作为测试添加到您的 application.yml 中以自动选择它。

Spring : profiles.active: 测试

关于java - @SpringBootTest 使用测试属性(测试数据库)文件运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56041815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com