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

时间:2019-05-08 13:20:05

标签: java spring-boot testing

我在“ 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"),但没有用

1 个答案:

答案 0 :(得分:1)

运行Spring Profile测试。

-Dspring.profiles.active = test

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

春天:   profiles.active:测试