0

I have a service written in Kotlin, which doesn't let you assign a non-nullable parameter to null. Unfortunately, my client code is in a different language which doesn't care whatsoever for Kotlin's rules, so the service gets calls pretty frequently with null values in requests. These are currently not handled gracefully.

I need a way to integration test requests like this with null required parameters, but my integration tests are in Kotlin so I can't even instantiate these bad requests. Is there any way I can get Kotlin's null-safety to look the other way, just for the tests?

StolenKitten
  • 337
  • 1
  • 10
  • You can make nullable type in Kotlin – Shalu T D Jun 29 '20 at 15:57
  • How are the client and the server communicating? Is it over REST? – Todd Jun 29 '20 at 16:03
  • @ShaluTD Yes but I don't want to make my request fields nullable. For people using our Kotlin client, having non-nullable required fields in the request is great. – StolenKitten Jun 29 '20 at 16:03
  • @Todd yeah, it's JAX-RS based. – StolenKitten Jun 29 '20 at 16:04
  • 2
    Probably the easiest thing would be to write them in Java. maybe you can use a Java function to generate the "bad" request, and then have the rest of the tests in kotlin. (feel free to replace Java with Groovy or whatever else you know and compiles to JVM) – al3c Jun 29 '20 at 16:24
  • Yep this is what I'm going with! All I had to do is make a "NullableRequestGenerator" class in Java and get request objects from that in my Kotlin tests. Thanks! – StolenKitten Jun 29 '20 at 16:26

2 Answers2

0

When a creating a test that provides null required parameters add a ? after the return type of the function to allow it to return null. Then you can just return null from the function. See this answer.

0

@al3c had the answer but reposted it here for visibility.

The solution to this is to make a Java class that vends the bad requests like this

public BadRequestGenerator {     
    public static MyRequest getBadRequest() {
        return new MyRequest(null, null, null); // Set "required" params null
    }
}

And then just call that getBadRequest function in your Kotlin code.

You can also go a step further and have the Java method take params and pass them to the request constructor, even if you're calling it from Kotlin it preserves the nullability of the java code.

StolenKitten
  • 337
  • 1
  • 10