mercredi 8 mai 2019

@SpringBootTest runing with test-properties (test database) file

I had a project on "spring boot 2" and I want to test it. Table:

@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());
    }
}

Repository is CrudRepository<Contract, Long>:

Service:

@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);
    }
}

I wanting to test "Service" layer and testing it in the test database. Parameters of the test database available in the "application-test.properties", but I running test, "SpringBoot" used the real database from "application.properties".
Test:

@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());
    }
}

Pls, tell me, how do I switch to the test base? I trying @PropertySource("classpath:application-test.properties") and @TestPropertySource("classpath:application-test.properties"), but not work

Aucun commentaire:

Enregistrer un commentaire