Kotlin Mock Spring boot test can't compile - spring-boot

So I have the following test
#Test
fun `when save claims is called with email saved to that profile` () {
//arrange
given(profileRepository.findProfileByEmail(anyString())).willAnswer { daoProfile }
given(patientRepository.findById(anyInt())).willAnswer { Optional.of(daoPatient) }
given(claimRepository.saveAll(anyList())).willAnswer { mutableListOf(daoClaim) }
//act
val result = claimService.saveClaimsForEmail(listOf(dtoClaim), "Test#test.test")
//assert
assert(result != null)
assert(result?.isNotEmpty() ?: false)
verify(claimRepository).saveAll(anyList())
}
The line given(claimRepository.saveAll(anyList())).willAnswer { mutableListOf(daoClaim) } gives the folowing error
e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate expression: KtBlockExpression
File being compiled at position: (217,71) in /Users/archer/Work/masterhealth/master_billing/src/test/kotlin/com/masterhealthsoftware/master_billing/data/service/ClaimServiceTest.kt
The root cause java.lang.IllegalStateException was thrown at: org.jetbrains.kotlin.codegen.state.KotlinTypeMapper$typeMappingConfiguration$1.processErrorType(KotlinTypeMapper.kt:113)
...
Caused by: java.lang.IllegalStateException: Error type encountered: (???..???) (FlexibleTypeImpl).
at org.jetbrains.kotlin.codegen.state.KotlinTypeMapper$typeMappingConfiguration$1.processErrorType(KotlinTypeMapper.kt:113)
When the line is removed, it compiles but the test fails for obvious reasons.
claimRespoitory is annotated #MockBean at the top of the test class, and is a JpaInterface. Line 217 is the start of the function. I've also trie using when and other various willReturn or willAnswer....
Any idea why?

I was facing the same issue when using Mockito any(). Changing it to ArgumentMatchers.any(YourClass::class.java)) solved the compilation error, there is a deprecated ArgumentMatchers.anyListOf(YourClass::class.java) that might do the job.

Related

Error Handling / Throw error in Strapi 4.0

in Strapi 4.0, i want to validate the input before saving. So i created lifecycles.js file as per the documentation and added the code:
module.exports = {
beforeCreate(event) {
//validation login here;
if (!valid) {
throw strapi.errors.badRequest('Invalid Entry');
}
},
}
How ever throw strapi.errors.badRequest('Invalid Entry'); is giving an error :
Cannot read property 'badRequest' of undefined
My guess is the Strapi v4 changed it from version 3. I looked everywhere but couldn't find a solution.
Any idea on how to handle error in lifecycles.js?
I had a similar situation with a forbidden error. I got to do it importing a class from #strapi/utils/lib/errors.js
const { ForbiddenError } = require("#strapi/utils").errors;
...
if (!authorized) {
throw new ForbiddenError(errorMessage);
}
You can show the list of errors based on your requirement
const { ValidationError } = require("#strapi/utils").errors;
...
if (formValidationError) {
throw new ForbiddenError("Fill the form");
}
Strapi comes with a lot of error response functions here are they
HttpError,
ApplicationError,
ValidationError,
YupValidationError,
PaginationError,
NotFoundError,
ForbiddenError,
PayloadTooLargeError,
UnauthorizedError,
PolicyError,

How to Only Catch non-ApolloError Errors with Apollo GraphQL Server

I have an Apollo GraphQL server, where I want to only report internal server errors (not errors extending ApolloError like AuthenticationError, UserInputError, etc.).
Here is the plugin that I wrote that catches internal server errors and reports them:
const errorReportingPlugin = {
requestDidStart(_) {
return {
didEncounterErrors(ctx) {
// If we couldn't parse the operation, don't do anything
if (!ctx.operation) return
for (const err of ctx.errors) {
// Don't report errors extending ApolloError like AuthenticationError, UserInputError, etc.
if (err instanceof ApolloError) {
continue
}
// report error here...
}
}
}
}
}
However err instanceof ApolloError returns false when I throw AuthenticationError, which extends ApolloError.
So I tried to check the class of the err by printing the constructor name and I got GraphQLError.
console.log(err.constructor.name)
Does anyone know how to avoid reporting all errors extending ApolloError?
The solution is to check whether err.originalError (not err) is an instance of ApolloError like this:
if (err.originalError instanceof ApolloError) {
// don't report error since it is a user facing error like AuthenticationError, UserInputError, etc.
}
credit to #xadm

Unknown type name 'WINBOOL'

I'm trying to link psapi in to a kotlin-native application and I encountered this error that I don't know how to fix.
By the type of error it looks like I'm missing something in the linker options but I couldn't find any information about it.
build.gradle.kts:
plugins {
kotlin("multiplatform") version "1.3.50"
}
repositories {
mavenCentral()
}
kotlin {
mingwX64("HelloWorld") {
val main by compilations.getting
val psapi by main.cinterops.creating
binaries {
executable("HelloWorldApp") {
entryPoint = "sample.helloworld.main"
}
}
}
}
src/nativeInterop/cinterop/psapi.def:
headers = psapi.h
headerFilter = psapi/*
linkerOpts.mingw = -lpsapi
The actual exception message:
Exception in thread "main" java.lang.Error: C:\Users\pawer\.konan\dependencies\msys2-mingw-w64-x86_64-gcc-7.3.0-clang-llvm-lld-6.0.1-2\x86_64-w64-mingw32\include\psapi.h:75:3: error: unknown type name 'WINBOOL'
at org.jetbrains.kotlin.native.interop.indexer.UtilsKt.ensureNoCompileErrors(Utils.kt:146)
at org.jetbrains.kotlin.native.interop.indexer.IndexerKt.indexDeclarations(Indexer.kt:963)
at org.jetbrains.kotlin.native.interop.indexer.IndexerKt.buildNativeIndexImpl(Indexer.kt:952)
at org.jetbrains.kotlin.native.interop.indexer.NativeIndexKt.buildNativeIndex(NativeIndex.kt:91)
at org.jetbrains.kotlin.native.interop.gen.jvm.MainKt.processCLib(main.kt:222)
at org.jetbrains.kotlin.native.interop.gen.jvm.MainKt.interop(main.kt:38)
at org.jetbrains.kotlin.cli.utilities.InteropCompilerKt.invokeInterop(InteropCompiler.kt:69)
at org.jetbrains.kotlin.cli.utilities.MainKt.main(main.kt:18)
FAILURE: Build failed with an exception.
Problem solved
src/nativeInterop/cinterop/psapi.def:
headers = windows.h \ psapi.h
headerFilter = psapi.h
package = psapi
linkerOpts.mingw = -lpsapi

How to unit test graphql query/mutation error with Mocha and Chai?

Since graphql error is not an standard Error. It's a GraphQLError
I can't figure out how to write unit test when graphql query/mutation throw an exception.
Here is my try:
it('should throw an error when lack of "id" argument for user query', async () => {
const body = {
query: `
query user{
user {
id
name
}
}
`
};
try {
const actualValue = await rp(body);
} catch (err) {
logger.error(err);
}
// logger.info(actualValue);
expect(1).to.be.equal(1);
// expect(actualValue).to.throw()
});
I found some tests in graphql.js repo. https://github.com/graphql/graphql-js/blob/master/src/tests/starWarsQuery-test.js#L393
But I think the way they test the query/mutation error is not correct.
They just do a deep equal with the error. But before running the test suites, how do I know the error data structure like locations: [{ line: 5, column: 13 }],? Maybe I should use snapshot testing so that I don't need to know the error data structure?
Check this package https://github.com/EasyGraphQL/easygraphql-tester there is an example with mocha and chai on the documentation

SerializationException in Parse cloud code. mdhost.exe crashes

Setting up an nunit test project for some parse cloud code. Testing the hello world example cloud function I receive the following unhandled exception in Xamarin studio. (Test has passed a few times, but still receive exception)
SerializationException: Type 'Parse.ParseException' in Assembly 'Parse, Version=1.5.4.0, Culture=neutral, PublicKeyToken=ba48c3a442de616e' is not marked as serializable.
Also, mdhost.exe crashes a few seconds after the test runs.
Here is the Nunit test code.
[Test()]
public async void HelloTest(){
IDictionary<string, object> param = new Dictionary<string, object> ();
await ParseCloud.CallFunctionAsync<string>("hello",param).ContinueWith(t => {
string resp = t.Result;
Assert.AreEqual("Hello world!", resp);
});
}
I'm running Xamarin Studio 5.9.5 (build 9) on win7
Copied code over to Xamarin 5.9.4 (build 5) on mac. Test runs and passes without getting mdhost.exe crash. However still showing SerializationException.
(Misread your question on the first answer)
Your Parse call is failing with a Parse.ParseException and that exception is what is trying to be serialized/deserialized. Wrapping a try/catch and Asserting the exception should work in order to show the error code what is actually failing in the test. (I can not get a real Parse ParseException to throw but this should get you started).
Than you can lookup the code:
[Test ()]
public async void HelloTest ()
{
IDictionary<string, object> param = new Dictionary<string, object> ();
try {
await ParseCloud.CallFunctionAsync<string> ("hello", param).ContinueWith (t => {
string resp = t.Result;
Assert.AreEqual ("Hello world!", resp);
});
} catch (ParseException ex) {
Assert.Fail (String.Format("{0} : {1}", ex.Code, ex.Message));
} catch (Exception ex) {
Assert.Fail (ex.Message);
}
}

Resources