Hi everyone I am working on a mock test, m y class extends of GroovyTestCase and I am trying to set up a property in the the void setUp method as you can see in:
void setUp()
{
def slurper = new JsonSlurper()
inData = slurper.parse( new File( "src/test/resources/fixtures/v1/watch/20160511_watch_listings_live_in.json" ), 'UTF-8' )
outData = slurper.parse( new File( "src/test/resources/fixtures/v1/watch/20160511_watch_listings_live_out.json" ), 'UTF-8' )
watchPresenter = BinderTestUtils.instanceForLibraryNamed( "dang_v1_watch_presenter" )
watchPresenter.localTranslate = new LocalTranslateHelperTest( )
//def info = [ mapper: mapperMock]
//watchPresenter:[localTranslate:new LocalTranslateHelperTest( )]
println("watchPresenterTranslate:" + watchPresenter.localTranslate.getStrings("en"))
}
But I am getting the next error:
Cannot set readonly property: localTranslate for class WatchListingPresenterTests.
Do you know if is possible to set up a readOnly property as in this case?
In the real class I am using the localTranslate script just like this:
def strings = this.localTranslate.getStrings( params["lang"] )
I need to mock this property, but I am getting this error.
Thanks in advance.
I solved this problem using the metaClass for get/setProperty. The documentation about runtime metaprogramming is in the next link:
http://groovy-lang.org/metaprogramming.html
My solution was very simple as you can see:
watchPresenter.metaClass .localTranslate = new LocalTranslateHelperTest( )
And that worked perfectly.
Thanks anyway.
Related
I'm trying to get a Groovy script that runs as a post-build step in a Jenkins job to access an injected variable but it keeps getting null.
I've kept the job as simple as possible so there are only 2 real bits of configuration to consider.
Here's how the property is injected. I could use other methods but this is intended for a more complicated job that reads in external properties.
This is the Groovy script I have so far. It will do something else with the value once it gets it.
This is the logging from running the job.
I'm not a Groovy expert and I've searched and tried a number of things but without success.
Of course having posted a question I then got the answer myself...
New script:
New logging:
I was able to set the value of the variable in Jenkins and access them in Slack notifications using the below script in Groovy PostBuild:
import hudson.model.*
import hudson.EnvVars
manager.listener.logger.println("======Search Log=======");
def total_tests_count=0
def total_pass_count = 0
def total_failed_count = 0
def total_skipped_count=0
def myVar
def envVar
def newEnv
def matcher = manager.getLogMatcher(".*Tests Summary(.*)\$")
if(matcher?.matches()) {
// manager.addShortText(matcher.group(1), "grey", "white", "0px", "white")
manager.listener.logger.println("matcher-0=== "+matcher.group(0));
manager.listener.logger.println("matcher-1 ====== "+matcher.group(1));
int total_start = matcher.group(1).indexOf("Total:")
total_tests_count = matcher.group(1).split('Total:')[1].split('Passed:')[0]
manager.listener.logger.println("extracted total_tests_count : ${total_tests_count}")
// Sets env var for total_tests_count
TOTAL_TESTS_COUNT=0
myVar = total_tests_count;
envVar = new EnvVars([TOTAL_TESTS_COUNT: myVar]);
newEnv = Environment.create(envVar);
manager.build.environments.add(0, newEnv);
int passed_start = matcher.group(1).indexOf("Passed:")
total_pass_count = matcher.group(1).split('Passed:')[1].split('Failed:')[0]
manager.listener.logger.println("extracted total_pass_count : ${total_pass_count}")
// Sets env var for total_pass_count
TOTAL_PASS_COUNT=0
myVar = total_pass_count;
envVar = new EnvVars([TOTAL_PASS_COUNT: myVar]);
newEnv = Environment.create(envVar);
manager.build.environments.add(1, newEnv);
int failed_start = matcher.group(1).indexOf("Failed:")
total_failed_count = matcher.group(1).split('Failed:')[1].split('Skipped:')[0]
manager.listener.logger.println("extracted total_failed_count : ${total_failed_count}" )
// Sets env var for total_failed_count
TOTAL_FAILED_COUNT=0
myVar = total_failed_count;
envVar = new EnvVars([TOTAL_FAILED_COUNT: myVar]);
newEnv = Environment.create(envVar);
manager.build.environments.add(2, newEnv);
int skipped_start = matcher.group(1).indexOf("Skipped:")
total_skipped_count = matcher.group(1).split('Skipped:')[1]
manager.listener.logger.println("extracted total_skipped_count : ${total_skipped_count}")
// Sets env var for total_skipped_count
TOTAL_SKIPPED_COUNT=0
myVar = total_skipped_count;
envVar = new EnvVars([TOTAL_SKIPPED_COUNT: myVar]);
newEnv = Environment.create(envVar);
manager.build.environments.add(3, newEnv);
}
In Jenkins, I was able to access using custom message:
Please check below url for test automation output for PR build
Total Cases: $TOTAL_TESTS_COUNT, Passed:$TOTAL_PASS_COUNT, Failed: $TOTAL_FAILED_COUNT, Skipped: $TOTAL_SKIPPED_COUNT.
I'm trying to write white test to test my API with file uploads.
I'm following the docs about this using basic client request, not crawler.
The unit test is:
class RecordsControllerTest extends WebTestCase {
private $client;
public function __construct() {
parent::__construct();
$this->client = self::createClient();
$this->client->insulate();
}
public function testApiPostUpload($params){
$fileToUpload = realpath(__DIR__.'/../../resources/mpthreetest.mp3');
$file = new UploadedFile(
$fileToUpload,
'mpthreetest.mp3',
MimeTypeGuesser::getInstance()->guess($fileToUpload),
filesize($fileToUpload)
);
$this->client->request('POST', '/records/'.$params['createdRecordId'].'/upload', array(), array('file' => $file) );
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
}
When I execute the test I receive an error:
Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
/path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:165
/path/to/project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:348
/path/to/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:143
/path/to/project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:313
/path/to/project/src/Bundle/Tests/Functional/Controller/RecordsControllerTest.php:182
I have found this question for about the same error, but in this case the request is not sent to the controller and the problem is not the entity and implementing serialization.
Anyone who knows how to fix this?
Anyone who managed to make unit test for uploading file in symfony 2?
You could try to NOT insulate the requests passing false as argument to the insulate method so try this:
$this->client->insulate(false);
instead of this:
$this->client->insulate();
Hope this help
I was able to resolve it by setting the changeHistory parameter to false (7th and last parameter in the request method signature):
$crawler = $client->request($form->getMethod(), $form->getUri(), $values, $files, [], null, false);
This will prevent the serialize on following lines :
if ($this->followRedirects && $this->redirect) {
$this->redirects[serialize($this->history->current())] = true;
return $this->crawler = $this->followRedirect();
}
I've following old method written in code, which is for accessing request object in service class such as:
def someServiceMethod() {
....
def webUtils = WebUtils.retrieveGrailsWebRequest()
def request = webUtils.getCurrentRequest()
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request
CommonsMultipartFile file = (CommonsMultipartFile) mpr.getFile("file")
....
}
This is my unit test code for serivce class.
#TestFor(SomeService)
class SomeServiceSpec extends Specification {
void "test someServiceMethod"() {
given:
MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest()
FileInputStream inFile = new FileInputStream("./test-data/Hiearchy-003.xlsx") //valid file path
def multipartFile = new GrailsMockMultipartFile('file', 'file.xls', 'multipart/form-data', inFile)
request.addFile(multipartFile)
GrailsWebRequest webRequest = new GrailsWebRequest(
request,
new MockHttpServletResponse(),
new MockServletContext()
)
request.setAttribute(GrailsApplicationAttributes.WEB_REQUEST,webRequest)
RequestContextHolder.setRequestAttributes(webRequest);
when:
def result = service.someServiceMethod()
then:
result != null
//some more assertions
//..
}
}
I'm stuck with following error.
| Failure: test someServiceMethod(SomeServiceSpec)
| org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile#6ae8e5dd' with class 'org.codehaus.groovy.grails.plugins.testing.GrailsMockMultipartFile' to class 'org.springframework.web.multipart.commons.CommonsMultipartFile'
Anybody faced such issue before in grails unit test?
Instead of : GrailsMockMultipartFile,
use: org.springframework.mock.web.MockMultipartFile.
I just realised following line is just unnecessary if we use input stream direct it should not be problem hence solved my issue..
CommonsMultipartFile file = (CommonsMultipartFile) mpr.getFile("file")
I have this piece of code in a controller:
def update = {
Map model = [:]
model.foo = params.foo
model.bar = params.bar
def result = ""
MyObject obj = MyObject.findWhere(bar:bar, foo:foo)
MyObjectService.updateObj(model,obj)
result = true
render result as JSON
}
And this simple unit test:
def 'controller update'() {
given:
controller.params.foo = foo
controller.params.bar = bar
MyObject obj = new MyObject(bar:bar, foo:foo)
mockDomain(MyObject,[obj])
when:
controller.update()
then:
1 * MyObject.findWhere(bar:bar, foo:foo) >> obj
1 * MyObjectService.updateObj(model,obj)
and:
def model = JSON.parse(controller.response.contentAsString)
model == true
where:
foo = "0"
bar = "1"
}
Now this is failing by and it is telling me that, "not static method findWhere is applicable..." for those arguments. That "MyObject" is just an orm class, and when I run that application everything seems to be working fine, but the test is failing.
My logic is this:
I want to count how many times the findWhere and updateObj methods are call and I am also mocking their response. So findWhere will return the object I already mocked, and pass it on to the service.
Any ideas why this is failing ?
For mocking static methods you should use Spock's GroovyStub class which introduced in v0.7.
I am trying to deploy some code that does something simple, when the user clicks on the accept button, it checks a checkbox (I have a workflow set up on the checkbox) and then I need it to redirect me to a thank you page. At the moment I don't know if my code is correct so I need to get the test correct to test it.
My Apex class:
public class proposalCon {
ApexPages.StandardController stdCtrl;
Public List <PPM_Project__c> PPM_Project_List {get;set;}
public proposalCon(ApexPages.StandardController controller) {
stdCtrl= controller;
PPM_Project_List = [ select Short_Description__c from PPM_Project__c ];
}
public PageReference save(){
upsert PPM_Project_List;
PageReference reRend = new PageReference('/apex/final_approval_canvas_complete');
reRend.setRedirect(true);
return reRend;
}
}
And here is my test attempt:
#isTest
private class proposalConTest{
static testMethod void testProposalCon() {
// List of Message
List <PPM_Project__c> PPM_ProjectList = new List<PPM_Project__c>();
PPM_ProjectList.add(new PPM_Project__c (
Name = 'A Test' ,
Short_Description__c = 'Good Job',
Due_Date__c = system.today()+30,
Final_Design_Artwork__c ='http://proteusleadership.com/DE123'
));
PPM_ProjectList.add(new PPM_Project__c (
Name = 'A Test 2' ,
Short_Description__c = 'Good Job',
Due_Date__c = system.today()+30,
Final_Design_Artwork__c ='http://proteusleadership.com/DEf123'
));
insert PPM_ProjectList;
Account account = new Account(Name='Test Co Pty Ltd');
insert account;
Contact contact = new Contact(firstName='TestFN',LastName='TestLN',email='testfn.testln#test.com',AccountId=account.Id);
insert contact;
// ** Start Testing ***/
proposalCon controller = new proposalCon();
PageReference reRend = new PageReference('/apex/final_approval_canvas_complete');
reRend.setRedirect(true);
PPM_ProjectList = [ select Short_Description__c from PPM_Project__c ];
}
}
I have been trying with no luck and any help would be greatly appreciated.
Thank you.
Joe
You need to instantiate a Standard Controller (feeding it a list of PPM Projects) and then instantiate your custom controller extension - like this:
PPM_Project__c proj = new PPM_Project__c() //you may need further parameters here.
ApexPages.StandardController stdController = new apexPages.StandardController(proj);
proposalCon controller = new proposalCon (stdController);
Then you can save, rerender as you like. Let me know if this works - I haven't executed this code, but this is how I create my own controller extension tests.
This should at least compile. However, I think you may really want a StandardSetController.
The docs are here:
SalesforceDocs
To make a testmethod for the StandardSetController, use something like this:
//instantiate the ApexPages.StandardSetController with an array of projects
ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(PPM_ProjectList);
//create custom controller with the StandardSetController as a param
ProposalCon ext = new ProposalCon(stdSetController);
This guy has more details on how to create a test method for a StandardSetController (and other controllers)