Testing a Controller class when i try do to delete all records from my database via Spring's CrudRepository, but it seems like nothing is happening. It seems is not flushing by default.
I've never tried this repository in a real controller call in a browser just with Junit tests, but I think it would works fine! :)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
public class CostumerControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private CostumerService costumerService;
private Costumer costumer;
@Before
public void before() {
this.costumer = this.exampleBuilder();
costumerService.saveAll(this.costumer);
}
@After
public void after() {
costumerService.deleteAll();
}
@Test
public void Should_ReturnStandardError_When_NotFoundById() throws Exception {
//implementation
}
private Costumer exampleBuilder() {
Costumer costumer = new Costumer("Test", "Test", "Test", CostumerType.LEGAL_PERSON);
State state = new State("Example State");
City city = new City("Example Sity", state);
Address address = new Address("Example Address",
"Example Address", "Example Address",
"Example Address", city, costumer);
costumer.getAddresses().add(address);
return costumer;
}
}
@Service
@Transactional
public class CostumerService {
@Autowired
private CostumerRepository repository;
public void deleteAll() {
repository.deleteAll();
}
//another methods
}
The repository extending CrudRepository
@Repository
public interface CostumerRepository extends CrudRepository<Costumer, Integer> {
}
After enable to show sql hibernate.show_sql=true
based on @TheCoder comment, the result is:
The deleteAll()
on @After
:
@After
public void after() {
costumerService.deleteAll();
}
The output sql:
2019-02-27 06:07:06 - HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
costumer0_.id as id1_3_,
costumer0_.cpf_cnpj as cpf_cnpj2_3_,
costumer0_.email as email3_3_,
costumer0_.name as name4_3_,
costumer0_.type as type5_3_
from
costumers costumer0_
The deteleAll()
on @AfterTransaction
the output sql includes the delete query.
@AfterTransaction
public void afterTransatcion(){
// List<Costumer> costumers = costumerService.findAll();
costumerService.deleteAll();
}
Hibernate:
select
costumer0_.id as id1_3_,
costumer0_.cpf_cnpj as cpf_cnpj2_3_,
costumer0_.email as email3_3_,
costumer0_.name as name4_3_,
costumer0_.type as type5_3_
from
costumers costumer0_
Hibernate:
delete
from
phones
where
costumer_id=?
Hibernate:
delete
from
costumers
where
id=?
In my junit, after adding repository.deleteAllInBatch()
inside @BeforeEach
method worked for me. Faced this issue only during execution of junit.
@BeforeEach
public void config()
{
repository.deleteAllInBatch()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With