View Javadoc
1   /*
2    *    Copyright 2016-2025 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package issues.gh324.spring;
17  
18  import static org.assertj.core.api.Assertions.assertThat;
19  
20  import org.junit.jupiter.api.Test;
21  import org.springframework.beans.factory.annotation.Autowired;
22  import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23  
24  import issues.gh324.ObservableCache;
25  import issues.gh324.TestUtils;
26  
27  @SpringJUnitConfig(classes = TestConfiguration.class)
28  class SpringTransactionTest {
29  
30      @Autowired
31      private SpringNameService nameService;
32  
33      @Test
34      void testCacheWithCommit() {
35          nameService.resetDatabase();
36  
37          nameService.insertRecord();
38          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsFred);
39          assertThat(ObservableCache.getInstance().getHits()).isZero();
40  
41          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsFred);
42          assertThat(ObservableCache.getInstance().getHits()).isEqualTo(1);
43  
44          nameService.updateRecordAndCommit();
45          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsBarney);
46          assertThat(ObservableCache.getInstance().getHits()).isZero();
47  
48          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsBarney);
49          assertThat(ObservableCache.getInstance().getHits()).isEqualTo(1);
50      }
51  
52      @Test
53      void testCacheWithRollback() {
54          nameService.resetDatabase();
55  
56          nameService.insertRecord();
57          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsFred);
58          assertThat(ObservableCache.getInstance().getHits()).isZero();
59  
60          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsFred);
61          assertThat(ObservableCache.getInstance().getHits()).isEqualTo(1);
62  
63          nameService.updateRecordAndRollback();
64          assertThat(nameService.getRecord()).hasValueSatisfying(TestUtils::recordIsFred);
65          // should pull the result from cache as the transaction was rolled back
66          assertThat(ObservableCache.getInstance().getHits()).isEqualTo(2);
67      }
68  }