Skip to content

NullCheckAsSwitchCase using wrong case kind with switch statement #785

@protocol7

Description

@protocol7

What version of OpenRewrite are you using?

  • org.openrewrite:rewrite-core:8.56.1
  • org.openrewrite.recipe:rewrite-migrate-java:3.12.0

What is the smallest, simplest way to reproduce the problem?

The NullCheckAsSwitchCase recipe will insert the wrong case kind into an old style switch statement:

  @Test
  public void nullInSwitchStatement() {
    rewriteRun(
        spec -> spec.recipe(new NullCheckAsSwitchCase()),
        java(
            """
            package com.helloworld;

            public class Foo {
              public String bar(String foo) {
                if (foo == null) {
                  throw new RuntimeException("");
                }

                switch (foo) {
                  case "hello": return "world";
                  default: return "other";
                }
              }
            }
            """,
            """
            package com.helloworld;

            public class Foo {
              public String bar(String foo) {
                switch (foo) {
                  case null: throw new RuntimeException("");
                  case "hello": return "world";
                  default: return "other";
                }
              }
            }
            """));
  }
org.opentest4j.AssertionFailedError: [Unexpected result in "com/helloworld/Foo.java":
diff --git a/com/helloworld/Foo.java b/com/helloworld/Foo.java
index 18bc2a2..7daf815 100644
--- a/com/helloworld/Foo.java
+++ b/com/helloworld/Foo.java
@@ -2,8 +2,9 @@

 public class Foo {
   public String bar(String foo) {
+
     switch (foo) {
-      case null: throw new RuntimeException("");
+          case null -> throw new RuntimeException("");
       case "hello": return "world";
       default: return "other";
     }
]
expected:
  "package com.helloworld;

  public class Foo {
    public String bar(String foo) {
      switch (foo) {
        case null: throw new RuntimeException("");
        case "hello": return "world";
        default: return "other";
      }
    }
  }"
 but was:
  "package com.helloworld;

  public class Foo {
    public String bar(String foo) {

      switch (foo) {
            case null -> throw new RuntimeException("");
        case "hello": return "world";
        default: return "other";
      }
    }
  }"
	at org.openrewrite.test.RewriteTest.assertContentEquals(RewriteTest.java:622)
	at org.openrewrite.test.RewriteTest.rewriteRun(RewriteTest.java:511)
	at org.openrewrite.test.RewriteTest.rewriteRun(RewriteTest.java:130)

Metadata

Metadata

Labels

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions