A Mocked repository returns null - Springboot JUnit Mockito - mockito

Im trying to use the save from my repository EmpresaRepository, but it returns null, heres my repository
heres my repository
and this is my test
And this is the output

This is the expected behaviour.
By using #MockBean you create and add a Mock of your EmpresaRepository into the ApplicationContext.
This means you execute the ::save() Method of your mock which returns null bey default.
Rule of thumb: Never Mock the thing you want to test.
The test should work if you replace the #MockBean annotation with Autowired.
Btw. please don't post screenshots of your code. It's annoying to switch between different tabs and also I'm not able to copy parts of your code.

Related

Trying to inject an #Client in to a Groovy Function

I'm trying to write a Micronaut AWS Groovy Lambda which makes HTTPS calls out to another service. I have followed the MN Docs and have created my project using:
mn create-function hello-world -lang groovy
This gave me a skeleton "hello-world" project with a functional test that I can run.
I then tried to modify the Groovy function (hello.world.HelloWorldFunction) to inject an HTTP client with the intention of calling the API within my function:
import static io.micronaut.http.HttpRequest.GET
#Field #Inject #Client("https://www.googleapis.com/books/v1") RxHttpClient httpClient
Maybe<String> helloWorld() {
httpClient.retrieve(GET("/volumes?q=isbn:0747532699"))
.firstElement()
}
Having done this I now get an exception when I run the functional test:
08:51:25.269 [nioEventLoopGroup-1-5] ERROR
i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred:
Failed to inject value for field [httpClient] of class:
hello.world.HelloWorldFunction
Path Taken: HelloWorldFunction.httpClient
io.micronaut.context.exceptions.DependencyInjectionException: Failed to inject value for field [httpClient] of class:
hello.world.HelloWorldFunction
Path Taken: HelloWorldFunction.httpClient
I'm almost certainly doing something wrong, but I'm at a bit of a loss in terms of how to figure out what. Hence grateful for any pointers.
Many thanks,
Edd
Found the answer to this. It's a bug in 1.0.0.M1. It's already fixed in master though so can be worked around by building Micronaut from source and using that.
In addition I discovered that I was returning a type that is unsupported by Lambda functions (Maybe<String>). After building MN from master and changing this to a supported return type everything is now working.

Using Groovy create Project properties in SoapUI

I have 50+ tests in my current SoapUI workspace. I need to add a new project level parameter on all of these tests. Is there a way I can do this using the groovy console within SoapUI?
For example :
testRunner.testCase.testSuite.project.setPropertyValue( "SuperMan",("SuperMan"));
I can run this to create a property within the current working project.
Is there a way I can create this under all projects on my current workspace?
Thanks in advance.
Yes, We can do this but it's little tricky.
Way to do this:
Create a empty generic project in soapui, Add empty testsuite, add Empty testcase
In test case Add a groovy script step
Now paste this groovy code
for(project in com.eviware.soapui.SoapUI.workspace.projectList) {
if(project.open && project.name != testRunner.testCase.testSuite.project.name){
project.setPropertyValue( "TestProperty","TestValue");
}
}
Run the groovy step, you will get property added at Project level.
Please mark this as correct response if this solve your problem.
Using your testRunner access you simply need one level more workspace. From here you can access projects map and iterate over each project adding the property:
testRunner.testCase.testSuite.project.workspace.projects.each{ key, proj ->
proj.setPropertyValue('superman','superman')
}
This code doesn't add the property on closed projects in workspace but not fails accessing it.
Alternatively as #Rao suggest on his comment it's possible to use default it object iterator and access the value instead of defining key, proj -> on each:
testRunner.testCase.testSuite.project.workspace.projects.each{
it.value.setPropertyValue('superman','superman')
}
I prefer the first approach for clarity.
Hope it helps,

SoapUI: Pass property values to called test case

I am a beginner in soapui testing. Hopefully you can help me solving this problem.
In my test project I have a test suites which contains several test cases. Multiple test case will start the same test case. To run this test case I need some property values to be transferred to this test case.
I tried to achieve this in two ways. But I failed in both.
I tried to call the test case and set the needed properties in the test case. I start the test case from a Groovy script. But I couldn't find a good example how to set the properties in the called test case.
I tried to get the property values of the calling parent test case inside the called test case. It looks like the parent test case that called the test case isn't available in the context of the running test case.
The test cases, that will call the same test case, will be run in parallel. So, I think it isn't a solution to first set the property values and then start the test case, because they will be overwritten by the other test cases that run at the same time. Also using test suite properties for these values won’t work because of running the test cases in parallel.
My test project looks like this.
MyProject
TestSuite_APLtests
TestCase_user_01
Properties test step
Run_test <groovy script>
Step_01
…..
TestCase_user_02
Properties test step
Run_test <groovy script>
Step_01
…..
TestCase_General
Properties test step
POST sessions
Step_01
…..
The ‘Properties test step’ of each ‘TestCase_user_’ contains a user and password needed in test case ‘TestCase_General’ and will be different for each test case.
In the ‘Run_test’ groovy script of each ‘TestCase_user_’ the test case ‘TestCase_General’ is started by using:
def myTestSuite = testRunner.testCase.testSuite.project.getTestSuiteByName("TestSuite_APLtests")
def myTestCase = myTestSuite.getTestCaseByName("TestCase_General")
myTestCase.run(null, false)
How can I add the properties user and password to the run comment that starts the test case?
If I try to get the property values with a groovy script in test case ‘TestCase_General’ I don’t know how to determine which test case has called ‘TestCase_General’. I found some posts on internet that suggests to use: context.getProperty("#CallingRunTestCaseStep#") to determine the calling test case. But this value is null. And when I try to check if the calling test case is available in the context by using: context.hasProperty("#CallingRunTestCaseStep#") this is false, so this doesn't work to find the calling test case.
Can someone tell me what the solution will be to get this working.
Thanks,
You can set Test Case properties from groovy script with setPropertyValue(name,value) method, however if you run the Test Cases in parallel, this properties as you said will be overwritten for each Test Case calling TestCase_General. So instead of use setPropertyValue you can pass the context properties through the run(StringToObjectMap properties, boolean async) method in the WsdlTestCase.java class. Your groovy code to call TestCase_General could be:
import com.eviware.soapui.support.types.StringToObjectMap
// get test suite
def myTestSuite = testRunner.testCase.testSuite.project.getTestSuiteByName("TestSuite_APLtests")
// get your test case
def myTestCase = myTestSuite.getTestCaseByName("TestCase_General")
// set the user and password properties in the context
context.setProperty("user","userTestCaseN")
context.setProperty("password","passwordTestCaseN")
// run the testCase passing the context
def contextMap = new StringToObjectMap( context )
myTestCase.run(contextMap,false);
To access the context properties in the groovy script of your TestCase_General use this code:
context.getProperty("userPassword")
Or if you prefer to use context.expand:
context.expand('${#user}')
Note that the use of # depends on how you are accessing the properties.
If you also need to use the context properties in the SOAP Test Request of your TestCase_General use this way ${#propetryName} i.e:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Header/>
<Body>
<request>
<user>${#user}</user>
</request>
</Body>
</Envelope>
Hope this helps,

Using mockito is there a reason to nullify mocks in #After?

I'm wondering,
If in #Before method I'm initializing a mock objects, shouldn't I nullify references to it in #After ? Or would that be redundant? And why?
Not necessary, JUnit creates a new instance of the test per test method.
However if it's static fields it's another story, and proper lifecycle should be implemented, but I strongly advise you to not use static fields in a JUnit test ! Instead think about implementing your own JUnit Runner.
And for TestNG, it's a different story, as TestNG creates a single instance of the test, so you have to be careful there on the lifecycle of the mocks.
"Nullifying" reference doesn't change anything here.
#Before annotated method is ran before each test method. If you are initializing mocks in such method they will be reinitialized before each test. There is a different annotation - #BeforeClass, this annotation causes a method to be executed only once before execution of any test method in that test class. In this case however "nullifying" a reference will not help you because you still need to create a new mock object and assign its reference to your field.

Grails unit test for domain class insertBefore

How can I test the initBefore method of Groovy Domain-Classes with a unit test in Grails?
I created the dummy object but the beforeInsert-method is not called until myObject.save() is invoked and save is unavailable in the testing environments.
Edit: its a unit-test. there is no error, but the method beforeInsert is not called
beforeInsert is called during unit tests. I can verify this in my tests. A couple things to consider:
ensure you use a beforeInsert method, and not a closure. A closure will not work correctly.
it is called when the object is flushed, so perhaps you are having silent save errors beforehand. In your test when you save the object do .save(flush: true, failOnError: true)
Do you want test if the beforeInsert method is being called or the logic of beforeInsert is correct?
If you want to test if beforeInsert is being called the test class should extend the GrailsUnitTestCase. Do so should give you mocking capabilities and add all the methods like save() and validate(). You can verify if the mocked object called the beforeInsert method or not when you do a save().
If you are testing the logic of beforeInsert then you don't need to mock it. You can create the object and test the logic just like other unit test.
Hope this helps.
Just creat a domain object and save() it. Then check whether or not the "beforeInsert" manipulated your Object.
save() is available in the testing enviroments. Please show your Stacktrace when calling myDomainobject.save()
I had the same exact problem! In GORM (at least until the current version) the save method does not take effect immediately just because it is called! If you want it to take effect right away you need to specify flush:true like this domain.save(flush:true).
it says here http://grails.org/doc/2.2.x/ref/Domain%20Classes/save.html
The save method informs the persistence context that an instance
should be saved or updated. The object will not be persisted
immediately unless the flush argument is used:
To answer your question, beforeInsert is not called until the save is persisted (save takes effect) therefor you should invoke save with flush to test beforeInsert and beforeUpdate methods.
Hope this helps!

Resources