Last active
June 11, 2018 19:29
-
-
Save alwarren/070ac733d3c5a0a88e24f444f01b2768 to your computer and use it in GitHub Desktop.
A generic Kotlin wrapper class for determining the success or failure of some method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A generic wrapper class for determining the success or failure of some method | |
* | |
* In the business logic, examine the instance class to determine success or failure | |
* | |
* Example - | |
* <pre> | |
* <code> | |
* val result: ResponseObject = SomeRepository().getData(true) | |
* if (result is ResponseObject.Success) { | |
* println(SuccessMessage) | |
* } else { | |
* println(ErrorMessage) | |
* } | |
* </code> | |
* </pre> | |
*/ | |
sealed class ResponseObject { | |
/** | |
* A Success case | |
* | |
* Adjust parameters as needed | |
*/ | |
class Success(val message: Any) : ResponseObject() | |
/** | |
* An Error case | |
* | |
* Adjust parameters as needed | |
*/ | |
class Error(val message: Any) : ResponseObject() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ResponseObjectTest { | |
private val successCase = true | |
private val errorCase = false | |
private val repository = SomeRepository() | |
@Test | |
fun response_should_be_success() { | |
val response = repository.getData(successCase) | |
assertThat(response, instanceOf(ResponseObject.Success::class.java)) | |
} | |
@Test | |
fun response_should_be_error() { | |
val response = repository.getData(errorCase) | |
assertThat(response, instanceOf(ResponseObject.Error::class.java)) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeRepository : Repository { | |
override fun getData(success: Boolean): ResponseObject { | |
if (success) return ResponseObject.Success(SuccessMessage) | |
return ResponseObject.Error(ErrorMessage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment