I'm testing my spring application, but there is wired thing. I can't find out why this happens.
in my spring code, I save requestBody into db using crudRepository. and I could find saved item with crudRepository. but when I run unittest and invoke same method with TestRestTemplate, I can't find saved item with crudRepository.
server
@PostMapping("")
public Question saveQuestion(@RequestBody Question question) {
questionRepository.save(question);
for(Question _p:questionRepository.findAll()) {
Application.LOG.info("[saveQuestion] "+_p.toString());
}
// I can find saved Question
return question;
}
unittest
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional
public class QuestionControllerTest {
@Autowired TestRestTemplate restTemplate;
@Autowired QuestionRepository questionRepository;
@Test
public void addNewQuestionTest() throws InterruptedException {
String json= "{"uniqueId":1}";
HttpEntity<String> req = new HttpEntity<>(json, headers);
ResponseEntity<Question> response = restTemplate.postForEntity("/question", req, Question.class);
for(Question _p:questionRepository.findAll()) {
Application.LOG.info("[addNewQuestion]"+_p.toString());
}
// I can't find saved question.
}
}
log looks like this.
[saveQuestion] Question(0)
[saveQuestion] Question(1)
[addNewQuestionTest] Question(0)
but I excepted
[saveQuestion] Question(0)
[saveQuestion] Question(1)
[addNewQuestionTest] Question(0)
[addNewQuestionTest] Question(1)
I checked db has data and saveQuestion method prints 2 items. but there is only 1 item in addNewQuestionTest method.
Am I missing something?