initializeError while Unit-testing Mock objects with Mockito in Xtend - unit-testing

I'm trying to run this unit test, I'm currently using Xtend over Java in order to read the code easily.
The test consist on an admin who must verify a user in order to add it or not to the current repository. I want to make that admin a mock object in order to verify if the user has send correctly the method "generateProfile", which do the following
class User{
#Accessors
repositoryAdministrator admin
def generateProfile{
admin.add(this)
}
the method add is the following:
class repositoryAdministrator{
#Accessors List<User> objects
#Accessors List<User> usersToValidate
def add(User user){
usersToValidate.add(user)
}
This is the test i want to run using the lib Mockito
#RunWith(MockitoJUnitRunner)
class MockitoTests{
val lala = new User()
#Mock
repositoryAdministrator fakeAdmin
#Before
def void init(){
MockitoAnnotations.initMocks(this)
}
#Test
def validationTest(){
lala.admin = fakeAdmin
lala.generateProfile
Mockito.verify(fakeAdmin).add(lala)
}
}
I have imported correctly the libraries, I'm working on an Eclipse IDE, and when i run the test I keep on getting initializationError.
How do I properly initialize a mock object using Mockito? Sorry for my English

I've already found the problem, test using Xtend are not necessary to define the return type... Until you implement Mockito dependencies on a Maven proyect. There was a problem in the add method of the admin, it return a bool variable and it should return void, the way to fix it was:
#RunWith(MockitoJUnitRunner)
class MockitoTests{
val lala = new User()
#Mock
repositoryAdministrator fakeAdmin
#Before
def void init(){
MockitoAnnotations.initMocks(this)
}
#Test
def void validationTest(){
lala.admin = fakeAdmin
lala.generateProfile
Mockito.verify(fakeAdmin).add(lala)
}
}
I only define the return type in the test, which should be in this case void

Related

Mock view helper in Zend Framework 3 in PHPUnit test

I want to test a specific controller action in Zend Framework 3. Because I use ZfcUser (https://github.com/ZF-Commons/ZfcUser) and Bjyauthorize (https://github.com/bjyoungblood/BjyAuthorize) I need to mock some view helpers. For example I need to mock isAllowed view helper and let it return true always:
class MyTest extends AbstractControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(include 'config/application.config.php');
$bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php');
$serviceManager = $bootstrap->getServiceManager();
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$mock = $this->getMockBuilder(IsAllowed::class)->disableOriginalConstructor()->getMock();
$mock->expects($this->any())->method('__invoke')->willReturn(true);
$viewHelperManager->setService('isAllowed', $mock);
$this->getApplication()->getServiceManager()->setAllowOverride(true);
$this->getApplication()->getServiceManager()->setService('ViewHelperManager', $viewHelperManager);
}
public function testViewAction()
{
$this->dispatch('/myuri');
$resp = $this->getResponse();
$this->assertResponseStatusCode(200);
#$this->assertModuleName('MyModule');
#$this->assertMatchedRouteName('mymodule/view');
}
}
In my view.phtml (which will be rendered by opening/dispatching /myuri uri) I call the view helper $this->isAllowed('my-resource').
But I got response code 500 with failing exception when executing testViewAction():
Exceptions raised:
Exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'A plugin by the name "isAllowed" was not found in the plugin manager Zend\View\HelperPluginManager' in ../vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php:131
How can I inject my isAllowed mock to the view helper manager in a way, that let the test case (testViewAction / $this->dispatch()) pass.
As stated in the previous answer already, we need to override the ViewHelper within the ViewHelperManager in the application object. The following code shows how this could be achieved:
public function setUp()
{
$this->setApplicationConfig(include 'config/application.config.php');
$bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php');
$serviceManager = $bootstrap->getServiceManager();
// mock isAllowed View Helper of Bjyauthorize
$mock = $this->getMockBuilder(IsAllowed::class)->disableOriginalConstructor()->getMock();
$mock->expects($this->any())->method('__invoke')->willReturn(true);
// inject the mock into the ViewHelperManager of the application
$this->getApplication()->getServiceManager()->get('ViewHelperManager')->setAllowOverride(true);
$this->getApplication()->getServiceManager()->get('ViewHelperManager')->setService('isAllowed', $mock);
}
ViewHelperManager is an other instance of service manager. and it's not allowed to override source code. Can you try "setAllowOverride" before "setService" method?

Unit test fails

I am new in Grails, I want to write unit tests for services using Spock. However I have the following issue.
import grails.transaction.Transactional
#Transactional
class BService {
boolean createB(){
return true
}
...
}
For this class I wrote the following test:
class BServiceTest extends Specification {
def "test createB"(){
given:
def service = new BService()
when:
def boolean temp
temp = service.createB()
then:
temp == true
}
}
The error I am getting when I run this test is the following:
java.lang.IllegalStateException: No transactionManager was specified. Using #Transactional or #Rollback requires a valid configured transaction manager. If you are running in a unit test ensure the test has been properly configured and that you run the test suite not an individual test method.
and it shows in GrailsTransactionTemplate.groovy:60
I would really appreciatie if anyone can give me a hint.
Add a #TestFor(BService) annotation to your unit test and use the instance of the service that it automatically provides. See http://grails.github.io/grails-doc/3.0.x/guide/testing.html for more information on testing.
Thank you ataylor for your reply. However I did a mistake, so I am now ansewring my own question.
First of all, the name conversion is wrong. When I create a service in grails there is automatically set a unit-test for this, so in that case I would have:
#TestFor(BService)
class BServiceSpec extends Specification {
def setup() {
User u = new User(1)
u.save()
}
def cleanup() {
}
def "test something"(){
}
}
In this case when I write a unit test, it runs.
The test that I had before was a functional test where I could not pass objects from the domain, so I had an error of the transactional manager.

Unit Testing of a model in Play Framework 2.3

We recently moved from Play Framework 2.1 to 2.3 and some unit test stops working.
In this particular unit test, I'm using an object that extends Model from ebean. I make sure not to use any function from ebean (like find(), save() or update()).
Unfortunately, just by creating my object, I get an exception because it try to initiate the Model.Finder member, which I'm pretty sure it wasn't doing before the migration. How can I overcome this?
My setUp function that throw exception on the new call.
#Before
public void setUp() throws Exception {
SignageScheduleEntry allTheTimeSchedule = new SignageScheduleEntry();
}
My object itself, it fails on the new Model.Finder when debugging the unit test:
public static Model.Finder<Long,SignageScheduleEntry> find = new Model.Finder<>(Long.class, SignageScheduleEntry.class);
public SignageScheduleEntry() throws InvalidPeriodException {
....
}
In brief, I want to use my object without the ebean crap in my unit test like any object in any unit test. How can I achieve this?
Thanks!
As shown here:https://github.com/jamesward/play2torial/blob/master/JAVA.md#create-a-model
You will need to create a "fakeApplication" like so:
import org.junit.Test;
import static play.test.Helpers.fakeApplication;
import static play.test.Helpers.running;
import static org.fest.assertions.Assertions.assertThat;
import models.Task;
public class TaskTest {
#Test
public void create() {
running(fakeApplication(), new Runnable() {
public void run() {
Task task = new Task();
task.contents = "Write a test";
task.save();
assertThat(task.id).isNotNull();
}
});
}
}
If that doesn't work, or if that's not what you're looking for, another approach is more complex and convoluted from the Play Java docs:
https://www.playframework.com/documentation/2.3.x/JavaTest#Unit-testing-models
You basically have to create a wrapper for the Model, and mock out the wrapper in the unit tests.

Mock a method for Grails Unit Test

In one of my unit tests, I am having some difficulty getting a mocked method to executed. I have the following test code:
void testExample() {
def mockICFService = new MockFor(ICFService)
...
//Mock the methods
controller.metaClass.icfList = { def person ->
println "icfList"
return [new IC(conceptId:'12345')]
}
mockICFService.demand.getAllIC(1..1) { def id, def withHist, def appId ->
println "mocking service"
return new Person()
}
...
def model = controller.detail()
}
Inside of detail in my controller class I create a Person via the ICFService's getAllIC(). This part works correctly. Later in the function, however, there is a call to icfList (which is defined in the controller). Through println's I have determined that the call is still being made, although it is returning an empty array. I believe that this is because the array is populated based on data in the servletContext, but in Unit Testing there is no access to that (hence my trying to mock it out).
Does anyone know how to force the test to use the mocked version of controller.icfList instead of calling the actual method in controller?
When I try your code, what blows up for me is the mocked service, and the part that works properly is the mocked-out icfList() method. The opposite of your observation, interestingly. For what it's worth, here's what I did:
First replace new MockFor() class instantiation with the mockFor() method. Then you need to inject the mock service into the controller.
def mockICFService = mockFor(ICFService)
controller.iCFService = mockICFService.createMock()
By doing the above, only the mocked versions of icfList() and getAllIC() get called, so you are not using the servletContext at all. Check out the Grails testing documentation for more info.

Grails Controller Testing - Problems with dynamic methods

I'm running some old (but valid, i'm told) tests on a legacy application, and notice that many of them arent working. The error message usually is 'No method signature for some dymamic method'
After using mockDomain I managed to solve that problem.
However, I can't figure out how to test controllers that create objects inside.
For example, I created a sample controller (omitted import statements)
package com.tmp
class DummyController2 {
def index = { }
def createObject={
def emp= new Emp(name:'name',description:'description')
if (emp.validate()){
render 'OK'
}
else{
render 'FAIL'
}
}
}
And then the sample controllerTest
package com.tmp
class DummyController2Tests extends ControllerUnitTestCase{
DummyController2 controller
public void setUp(){
super.setUp()
controller = new DummyController2()
}
public DummyController2Tests(){
super(DummyController2Tests)
}
public void tearDown(){
super.tearDown()
}
void testCreateObject(){
assertEquals 'OK',controller.createObject()
}
}
Now when I run this test, I get the
groovy.lang.MissingMethodException: No
signature of method: Emp.validate() is
applicable for argument types: ()
values: []
Is there a workaround on this? Adding mockDomain statements inside the controller seems very intrusive and wrong. Maybe its just that I'm using an old grails (1.2.1)?
Thanks in advance
Your domain class is not mocked. Add to setUp():
mockDomain Emp