How to test Spring transactions












1















I'm working to a project with Spring Boot 2.1.0 and I've the following situation.



I've the following repository



@Repository
public interface ActivityRepository extends PagingAndSortingRepository<Activity, Long> {

@Transactional
@Modifying
@Query("") // Imagine a query
void updateBacklogStatusAge();

@Transactional
@Modifying
@Query("QUERY 2") // Imagine a query
void updateNextStatusAge();

@Transactional
@Modifying
@Query("QUERY 3") // Imagine a query
void updateInProgressStatusAge();
}


and the following component



@Component
public class ColumnAgeJob {

private final ActivityRepository activityRepository;

public ColumnAgeJob(final ActivityRepository pActivityRepository) {
activityRepository = pActivityRepository;
}

@Transactional
public void update() {
activityRepository.updateBacklogStatusAge();
activityRepository.updateNextStatusAge();
activityRepository.updateInProgressStatusAge();
}
}


Now I want to test if the transactional annotation is working.



Basically my goal is to check if a runtimeException raised during the updateInProgressStatusAge() call will cause a rollback of updateNextStatusAge and updateBacklogStatusAge modifications.



How can I do that?
Thank you










share|improve this question



























    1















    I'm working to a project with Spring Boot 2.1.0 and I've the following situation.



    I've the following repository



    @Repository
    public interface ActivityRepository extends PagingAndSortingRepository<Activity, Long> {

    @Transactional
    @Modifying
    @Query("") // Imagine a query
    void updateBacklogStatusAge();

    @Transactional
    @Modifying
    @Query("QUERY 2") // Imagine a query
    void updateNextStatusAge();

    @Transactional
    @Modifying
    @Query("QUERY 3") // Imagine a query
    void updateInProgressStatusAge();
    }


    and the following component



    @Component
    public class ColumnAgeJob {

    private final ActivityRepository activityRepository;

    public ColumnAgeJob(final ActivityRepository pActivityRepository) {
    activityRepository = pActivityRepository;
    }

    @Transactional
    public void update() {
    activityRepository.updateBacklogStatusAge();
    activityRepository.updateNextStatusAge();
    activityRepository.updateInProgressStatusAge();
    }
    }


    Now I want to test if the transactional annotation is working.



    Basically my goal is to check if a runtimeException raised during the updateInProgressStatusAge() call will cause a rollback of updateNextStatusAge and updateBacklogStatusAge modifications.



    How can I do that?
    Thank you










    share|improve this question

























      1












      1








      1








      I'm working to a project with Spring Boot 2.1.0 and I've the following situation.



      I've the following repository



      @Repository
      public interface ActivityRepository extends PagingAndSortingRepository<Activity, Long> {

      @Transactional
      @Modifying
      @Query("") // Imagine a query
      void updateBacklogStatusAge();

      @Transactional
      @Modifying
      @Query("QUERY 2") // Imagine a query
      void updateNextStatusAge();

      @Transactional
      @Modifying
      @Query("QUERY 3") // Imagine a query
      void updateInProgressStatusAge();
      }


      and the following component



      @Component
      public class ColumnAgeJob {

      private final ActivityRepository activityRepository;

      public ColumnAgeJob(final ActivityRepository pActivityRepository) {
      activityRepository = pActivityRepository;
      }

      @Transactional
      public void update() {
      activityRepository.updateBacklogStatusAge();
      activityRepository.updateNextStatusAge();
      activityRepository.updateInProgressStatusAge();
      }
      }


      Now I want to test if the transactional annotation is working.



      Basically my goal is to check if a runtimeException raised during the updateInProgressStatusAge() call will cause a rollback of updateNextStatusAge and updateBacklogStatusAge modifications.



      How can I do that?
      Thank you










      share|improve this question














      I'm working to a project with Spring Boot 2.1.0 and I've the following situation.



      I've the following repository



      @Repository
      public interface ActivityRepository extends PagingAndSortingRepository<Activity, Long> {

      @Transactional
      @Modifying
      @Query("") // Imagine a query
      void updateBacklogStatusAge();

      @Transactional
      @Modifying
      @Query("QUERY 2") // Imagine a query
      void updateNextStatusAge();

      @Transactional
      @Modifying
      @Query("QUERY 3") // Imagine a query
      void updateInProgressStatusAge();
      }


      and the following component



      @Component
      public class ColumnAgeJob {

      private final ActivityRepository activityRepository;

      public ColumnAgeJob(final ActivityRepository pActivityRepository) {
      activityRepository = pActivityRepository;
      }

      @Transactional
      public void update() {
      activityRepository.updateBacklogStatusAge();
      activityRepository.updateNextStatusAge();
      activityRepository.updateInProgressStatusAge();
      }
      }


      Now I want to test if the transactional annotation is working.



      Basically my goal is to check if a runtimeException raised during the updateInProgressStatusAge() call will cause a rollback of updateNextStatusAge and updateBacklogStatusAge modifications.



      How can I do that?
      Thank you







      spring spring-boot spring-data-jpa spring-data spring-transactions






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 '18 at 18:50









      GaviGavi

      330215




      330215
























          2 Answers
          2






          active

          oldest

          votes


















          2














          You can use Mockito in order to change the behaviour of your service or repository by using @SpyBean or @MockBean.



          Unfortunately @SpyBean do not works on JPA repository (https://github.com/spring-projects/spring-boot/issues/7033, this issue is for Spring boot 1.4.1, but I have the same problem with 2.0.3.RELEASE)



          As workaround you can create a test configuration to create manually your mock:



          @Configuration
          public class SpyRepositoryConfiguration {

          @Primary
          @Bean
          public ActivityRepository spyActivityRepository(final ActivityRepository real)
          return Mockito.mock(ActivityRepository.class, AdditionalAnswers.delegatesTo(real));
          }
          }


          And in your test:



          @Autowired
          private ActivityRepository activityRepository;
          ....
          @Test
          public void testTransactional() {
          Mockito.doThrow(new ConstraintViolationException(Collections.emptySet())).when(activityRepository).updateInProgressStatusAge();

          activityRepository.updateBacklogStatusAge();
          activityRepository.updateNextStatusAge();
          activityRepository.updateInProgressStatusAge();

          // verify that rollback happens
          }





          share|improve this answer































            0














            You can change your method to test your transactional annotation.



            @Transactional
            public void update() {
            activityRepository.updateBacklogStatusAge();
            activityRepository.updateNextStatusAge();
            throw Exception();
            activityRepository.updateInProgressStatusAge();
            }


            This will simulate your desired scenario.






            share|improve this answer
























            • I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

              – Gavi
              Nov 19 '18 at 21:06











            • Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

              – uğur taş
              Nov 19 '18 at 23:34













            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53380923%2fhow-to-test-spring-transactions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            You can use Mockito in order to change the behaviour of your service or repository by using @SpyBean or @MockBean.



            Unfortunately @SpyBean do not works on JPA repository (https://github.com/spring-projects/spring-boot/issues/7033, this issue is for Spring boot 1.4.1, but I have the same problem with 2.0.3.RELEASE)



            As workaround you can create a test configuration to create manually your mock:



            @Configuration
            public class SpyRepositoryConfiguration {

            @Primary
            @Bean
            public ActivityRepository spyActivityRepository(final ActivityRepository real)
            return Mockito.mock(ActivityRepository.class, AdditionalAnswers.delegatesTo(real));
            }
            }


            And in your test:



            @Autowired
            private ActivityRepository activityRepository;
            ....
            @Test
            public void testTransactional() {
            Mockito.doThrow(new ConstraintViolationException(Collections.emptySet())).when(activityRepository).updateInProgressStatusAge();

            activityRepository.updateBacklogStatusAge();
            activityRepository.updateNextStatusAge();
            activityRepository.updateInProgressStatusAge();

            // verify that rollback happens
            }





            share|improve this answer




























              2














              You can use Mockito in order to change the behaviour of your service or repository by using @SpyBean or @MockBean.



              Unfortunately @SpyBean do not works on JPA repository (https://github.com/spring-projects/spring-boot/issues/7033, this issue is for Spring boot 1.4.1, but I have the same problem with 2.0.3.RELEASE)



              As workaround you can create a test configuration to create manually your mock:



              @Configuration
              public class SpyRepositoryConfiguration {

              @Primary
              @Bean
              public ActivityRepository spyActivityRepository(final ActivityRepository real)
              return Mockito.mock(ActivityRepository.class, AdditionalAnswers.delegatesTo(real));
              }
              }


              And in your test:



              @Autowired
              private ActivityRepository activityRepository;
              ....
              @Test
              public void testTransactional() {
              Mockito.doThrow(new ConstraintViolationException(Collections.emptySet())).when(activityRepository).updateInProgressStatusAge();

              activityRepository.updateBacklogStatusAge();
              activityRepository.updateNextStatusAge();
              activityRepository.updateInProgressStatusAge();

              // verify that rollback happens
              }





              share|improve this answer


























                2












                2








                2







                You can use Mockito in order to change the behaviour of your service or repository by using @SpyBean or @MockBean.



                Unfortunately @SpyBean do not works on JPA repository (https://github.com/spring-projects/spring-boot/issues/7033, this issue is for Spring boot 1.4.1, but I have the same problem with 2.0.3.RELEASE)



                As workaround you can create a test configuration to create manually your mock:



                @Configuration
                public class SpyRepositoryConfiguration {

                @Primary
                @Bean
                public ActivityRepository spyActivityRepository(final ActivityRepository real)
                return Mockito.mock(ActivityRepository.class, AdditionalAnswers.delegatesTo(real));
                }
                }


                And in your test:



                @Autowired
                private ActivityRepository activityRepository;
                ....
                @Test
                public void testTransactional() {
                Mockito.doThrow(new ConstraintViolationException(Collections.emptySet())).when(activityRepository).updateInProgressStatusAge();

                activityRepository.updateBacklogStatusAge();
                activityRepository.updateNextStatusAge();
                activityRepository.updateInProgressStatusAge();

                // verify that rollback happens
                }





                share|improve this answer













                You can use Mockito in order to change the behaviour of your service or repository by using @SpyBean or @MockBean.



                Unfortunately @SpyBean do not works on JPA repository (https://github.com/spring-projects/spring-boot/issues/7033, this issue is for Spring boot 1.4.1, but I have the same problem with 2.0.3.RELEASE)



                As workaround you can create a test configuration to create manually your mock:



                @Configuration
                public class SpyRepositoryConfiguration {

                @Primary
                @Bean
                public ActivityRepository spyActivityRepository(final ActivityRepository real)
                return Mockito.mock(ActivityRepository.class, AdditionalAnswers.delegatesTo(real));
                }
                }


                And in your test:



                @Autowired
                private ActivityRepository activityRepository;
                ....
                @Test
                public void testTransactional() {
                Mockito.doThrow(new ConstraintViolationException(Collections.emptySet())).when(activityRepository).updateInProgressStatusAge();

                activityRepository.updateBacklogStatusAge();
                activityRepository.updateNextStatusAge();
                activityRepository.updateInProgressStatusAge();

                // verify that rollback happens
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 16:20









                ccardoneccardone

                413




                413

























                    0














                    You can change your method to test your transactional annotation.



                    @Transactional
                    public void update() {
                    activityRepository.updateBacklogStatusAge();
                    activityRepository.updateNextStatusAge();
                    throw Exception();
                    activityRepository.updateInProgressStatusAge();
                    }


                    This will simulate your desired scenario.






                    share|improve this answer
























                    • I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

                      – Gavi
                      Nov 19 '18 at 21:06











                    • Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

                      – uğur taş
                      Nov 19 '18 at 23:34


















                    0














                    You can change your method to test your transactional annotation.



                    @Transactional
                    public void update() {
                    activityRepository.updateBacklogStatusAge();
                    activityRepository.updateNextStatusAge();
                    throw Exception();
                    activityRepository.updateInProgressStatusAge();
                    }


                    This will simulate your desired scenario.






                    share|improve this answer
























                    • I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

                      – Gavi
                      Nov 19 '18 at 21:06











                    • Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

                      – uğur taş
                      Nov 19 '18 at 23:34
















                    0












                    0








                    0







                    You can change your method to test your transactional annotation.



                    @Transactional
                    public void update() {
                    activityRepository.updateBacklogStatusAge();
                    activityRepository.updateNextStatusAge();
                    throw Exception();
                    activityRepository.updateInProgressStatusAge();
                    }


                    This will simulate your desired scenario.






                    share|improve this answer













                    You can change your method to test your transactional annotation.



                    @Transactional
                    public void update() {
                    activityRepository.updateBacklogStatusAge();
                    activityRepository.updateNextStatusAge();
                    throw Exception();
                    activityRepository.updateInProgressStatusAge();
                    }


                    This will simulate your desired scenario.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 19 '18 at 20:24









                    uğur taşuğur taş

                    254213




                    254213













                    • I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

                      – Gavi
                      Nov 19 '18 at 21:06











                    • Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

                      – uğur taş
                      Nov 19 '18 at 23:34





















                    • I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

                      – Gavi
                      Nov 19 '18 at 21:06











                    • Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

                      – uğur taş
                      Nov 19 '18 at 23:34



















                    I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

                    – Gavi
                    Nov 19 '18 at 21:06





                    I see two problems on this approach. 1. Exception is not RuntimeException and if not specified in rollbackFor will not rollback anything. 2. This approach is not reproducible during the build, and if in the future there're some regressions we can't detect him

                    – Gavi
                    Nov 19 '18 at 21:06













                    Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

                    – uğur taş
                    Nov 19 '18 at 23:34







                    Any RuntimeException triggers rollback, and any checked Exception does not. This means you can use unchecked exceptions. I assumed you just want to see your code is working. If you want to write unit test it has different ways. You can check these links : link1 , link2, link3. Main points are explained in these links.

                    – uğur taş
                    Nov 19 '18 at 23:34




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53380923%2fhow-to-test-spring-transactions%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Academy of Television Arts & Sciences

                    L'Équipe

                    1995 France bombings