I have one parameterized method which accept string parameter and returns data upon passed param. I am using codeception framework for writing unit testing for php-zend project.
Method: getDataByView($view) $view can be default, all.
So I want mock this method such way it behave & return result based on passed params. I didnt get way in codeception framework so used phpunit code for that. But getting problems in that.
$map = array(
array('default', $default),
array('all', $all)
);
$mock = $this->getMockBuilder('ViewTable')
->setMethods(['getDataByView'])
->disableOriginalConstructor()
->getMock();
$mock->expects($this->any())
->method('getDataByView')
->will($this->returnValueMap($map));
Actually this code work as per my expectation. Since I am using setMethods() it calls the ViewTable class constructor. If I dont use setMethods then It doesn't call constructor.
Problems:
I want to mock only one method of class, so I have used
setMethods() but it calls mock class constructor. I dont want that.
How can it be solved in phpunit.
How to mock parameterized method in codeception framework.
Related
I am struggling to create a unit test that successfully mocks this line:
WarehouseId warehouseId = new WarehouseId(currentState.getBuilding().getCode());
The issue is that an object is being created in the parameter. Any iteration of attempting to mock the constructor is met with a null pointer exception. The object in my test case is not being initialized. I know this because I am able to mock the function call successfully:
log.info(currentState.getBuilding().getCode());
I have read PowerMockito and MockConstruction are two options, however I am unable to add powerMockito, and we are using an earlier version of Mockito. Are there any other ways of doing this?
In my prod code I have the following queryDsl query:
Collection<String> myList = new ArrayList<>();
myList.add("blue");
myList.add("green");
myList.add("yellow");
QAnimal qAnimal = QAnimal.animal;
return animalRepository.exists(
qAnimal.color.in(myList).and(
qAnimal.name.eq("animal_name")
)
);
I want to mock this queryDsl query using Mockito. In my test file, in the setup method I did:
Collection<Book> myList = new ArrayList<>();
myList.add("blue");
myList.add("green");
myList.add("yellow");
QAnimal qAnimal = QAnimal.animal;
when(qAnimal.color.in(myList)).thenReturn((Expressions.asBoolean(false)));
when(qAnimal.name.eq("animal_name")).thenReturn((Expressions.asBoolean(true)));
When running the test, I receive the following problem:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
I can't create a JPAQuery object, only use that kind of queries.
Why would you mock JPAQuery? At this point you're either testing the internals of Querydsl, or making sure that you wrote what you wrote. Just mock the entire AnimalRepository instead. And if you want to test animalRepository properly, its best to do so in an integration test that actually executes the query against a database. There is also the possibility to execute the query against mock data using querydsl-collections.
If you insist on mocking JPAQuery with Mockito stubs however, the easiest way to mock builder API's, like for example JPAQuery, is to use Answers.RETURNS_SELF as default stub.
For example, use the following to instantiate your queryMock:
#Mock(answer = Answers.RETURNS_SELF) JPAQuery queryMock;
Help me understand how to mock a service method inside a controller for unit testing in grails using JUnit
I was trying to write a unit test case for my controller "add".
void testAdd_UT_03(){
......declaring and assigning prerequisites
controller.add() // This is the controller i want to unit test
.... asserting
}
//Controller
def add{
def a =someService.method()
}
Inside controller, some service methods are getting called which in turn is using HQL statements. Since i could not find a way to deal with HQL statements in unit testing, i want to mock the service method itself. ( i want the service method to return the predefined output).
Could someone please explain how to achieve this?
Could you also explain when to use mockController? what we really achieve by mocking something? ( i dint get the real picture as i am entirely new to this)
Thanks in advance,
BK
you can add the following code in the setUp method of your test to mock the service method and when you call the method "add" method on your controller it will call the mocked service method.
def predifinedOutput
void setUp(){
def mockControl = mockFor(YourService)
//params are the parameters passed to the service method
mockControl.demand.yourServiceMethod(0..10) { params->
predifnedOutput = "predifinedOutput"
return "predefined output"
}
controller.yourService = mockControl.createMock()
}
I'm trying to write some basic backingBean tests but I'm stuck with mocking the UserContext and facesContext.
This code is in the code that I'm trying to test:
UserContext uc = ContextProvider.getContext();
Locale locale = uc.getLocale();
ResourceBundle bundle = ResourceBundle.getBundle("AppMessages", locale);
String message = bundle.getString("this.is.the.message.key");
In another block of code I've got the following:
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().redirect(handleRedirect("someString"));
How could I mock these in a standard jUnit test using only mockito? Or do I have to use something like PowerMock?
Mockito can't mock static methods. You have a few options though:
Extract the code under test to methods which takes the UserContext and ResourceBundle or FacesContext instances as arguments
Wrap the static method calls in a factory object, and pass the factory objact instance as an argument to the code under test
PowerMock is an option, but slows down test execution and in my opinion allows bad-practice solutions
Instead create mocks for yourself, you can use Apache MyFaces Test, which provided already prepared Mock Objects for JSF artifacts. It will work better in a more wide range of cases, with less effort.
I'm having trouble using Moq in a UnitTesting project with Ninject.
First a few lines about my solution. It contains several projects (BussinesLogic, DAL, Infrastructure...). My goal is to UnitTest the logic i'm using in BussinessLogic project.
The solution is basicly for a windows service, but i've put in the logic so it can be run standalone. I'm using Ninject and i specify weather i want to use the ProductionModule or the TestingModule (windows service uses ProductionModule, console app uses TestingModule)
I'm using a factory pattern to get ninject kernel whenever i need it inside my application.
My TestingModule inherits from NinjectModule where i override the Load() method and there i do the binding. For instance:
Bind<IStorageManager>().To<StubStorageManager>();
I have the StubStorageManager but it's empty. It contains just the declaration of methods from IStorageManager.
The thing i would like to do is (in laymans terms):
Create a unitTest where i would create a new kernel specifying the TestingModule as it's parameter. Then i would like to create a mock object (let's say a mock of IStorageManager) storageManagerMock. Some method in IStorageManager returns a messageObject so i would probably need to mock that too, couse the bussiness logic is doing something based on that messageObject. So i would like to somehow set properties to that message object and then call some businessLogic method on it, so i can see if the logic works correctly.
I hope i didn't complicate it too much.
Please bear with me, i'm completely new to mocking and dependency injection, but am willing to learn.
I doubt you really want to be using Ninject in your tests. The whole point of using ninject is that you can decouple everything. You also want to try and keep everything decoupled from the dependency container itself if possible. Pass it in if you have to, or pass in factories that create the required object and have the container pass in the factory.
I suspect you probably want to do something like this:
public void ATest(){
//create a mock StorageManager
var managerMock = new Mock<IStorageManager>();
//create a mock MessageObject to be used by business logic
var messageObjectMock = new Mock<MessageObject>();
//have the storage manager return the mock message when required
managerMock.Setup(x => x.GetMessageObject()).Returns(messageObjectMock.Object);
//set up message expectations
messageObjectMock.Setup(x => x.ThisValueExpected).Returns(10);
messageObjectMock.Setup(x => x.ThisFunctionShouldBeCalled()).Verifiable("Function not called.");
//thing to test
BusinessLogicObject blo = new BusinessLogicObject(managerMock.Object);
blo.DoTheThingImTesting();
//make sure the business logic called the expected function, or do whatever check you need...
messageObjectMock.Verify();
}