My objective is to Mock the private variable in method of a service class in Grails.
Here I tried bellow way in my test method:
given: 'Mocking of object'
def dataSource = Mock(TransactionAwareDataSourceProxy)
def db1 = Mock(Sql)
service.dataSource = dataSource
new Sql(dataSource) >> db1
List<GroovyRowResult> resultList = new ArrayList<>()
GroovyRowResult result = new GroovyRowResult(id: 0)
result.someAmount = 400
resultList.add(result)
db1.rows(_) >> resultList
In my service class my code is :
def db = new Sql(dataSource)
List<GroovyRowResult> resultList = db.rows("Select * from user_info")
Here, I successfully mocked the TransactionAwareDataSourceProxy named dataSource but I am failed to assign mock def db = new Sql(dataSource) into local private variable db.
I need bellow solution:
How to mock the private variable inside a method. Here, I am assigning Sql in private variable db in my service method
Thanks in advance
The simple answer is: You don't. Instead you refactor to be able to use dependency injection, i.e. pass the Sql instance into the method or into the class. Then you can easily mock it.
See also here and in the other answers linked off of that answer.
The "don't do this at home, kids" part which I do not recommend because it only works for Groovy classes under test and also helps establish bad design in your application code: You can use Spock's Groovy mocks in order to mock constructors. You could achieve the same for Java classes using Mockito, Powermock or my own tool Sarek. Sarek even works for JRE bootstrap classes, also final ones.
But whenever you need Groovy mocks or special add-on tools while writing Spock tests, it is usually a sign you should refactor instead. Only in rare cases where you need to mock something in third party code you are unable to modify, you might need such tools. But even then you can usually refactor your own code in order to access the third party code in such a way that you can inject the right kind of test double (mock, stub, spy) preconfigured to behave like you need it to.
Related
I'm doing my first test in Java, and I have a Shiro Security... I follow the tutorial (https://shiro.apache.org/testing.html) but says:
(this example uses EasyMock, but Mockito works equally as well):
Subject subjectUnderTest = createNiceMock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
Because I use Mockito I implement with
Subject mockSubject = mock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
But when I do it have this error
The method expect(boolean) is undefined for the type AdminControllerTest
And don't give me the posibility to import it. I don't know if expect is especific of EasyMock and if yes what I have to use in Mockito.
I search here and see more person doing it and always recomend use this expect
How to mock a shirosession?
If we look at this code example ...
Subject mockSubject = mock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
We can see that ...
You are using mockito syntax to do the mocking.
You are using easyMock syntax to configure the mock. It is not even in the dependency list, so this method is not found.
The solution is to use mockito syntax to configure the mock.
Subject mockSubject = mock(Subject.class);
when(mockSubject.isAuthenticated()).thenReturn(true);
This will make everything work as expected and your Subject will return true, when the isAuthenticated() method is called.
If you want to up your mockito game, try this resource, which comes with working github code examples.
abp.io framework - testing
I am trying to set an ApplicationService class.
The method I'm trying to test uses 'ObjectMapper.Map<classFrom, classTo>(obj)'
I have used NSubstitue as LazyServiceProvider, but I am unable to find the correct Substitute to create an ObjectMapper.
Has anyone done this?
We resolved the issue.
We used a substitute for LazyServiceProvider.
Then the key was using a very specific setup when the LazyServiceProvider is trying to create the Object Mapper (see the abp code).
_abpProvider = Substitute.For<IAbpLazyServiceProvider>();
_abpProvider.LazyGetService<IObjectMapper>(Arg.Any<Func<IServiceProvider, object>>()).Returns(_objectMapper);
This allowed us to set up our own ObjectMapper in our test method, and have it be used in our ApplicationService.
I'm using Jmeter to design a test that requires data to be randomly read from text files. To save memory, I have set up a "setUp Thread Group" with a BeanShell PreProcessor with the following:
//Imports
import org.apache.commons.io.FileUtils;
//Read data files
List items = FileUtils.readLines(new File(vars.get("DataFolder") + "/items.txt"));
//Store for future use
props.put("items", items);
I then attempt to read this in my other thread groups and am trying to access a random line in my text files with something like this:
(props.get("items")).get(new Random().nextInt((props.get("items")).size()))
However, this throws a "Typed variable declaration" error and I think it's because the get() method returns an object and I'm trying to invoke size() on it, since it's really a List. I'm not sure what to do here. My ultimate goal is to define some lists of data once to be used globally in my test so my tests don't have to store this data themselves.
Does anyone have any thoughts as to what might be wrong?
EDIT
I've also tried defining the variables in the setUp thread group as follows:
bsh.shared.items = items;
And then using them as this:
(bsh.shared.items).get(new Random().nextInt((bsh.shared.items).size()))
But that fails with the error "Method size() not found in class'bsh.Primitive'".
You were very close, just add casting to List so the interpreter will know what's the expected object:
log.info(((List)props.get("items")).get(new Random().nextInt((props.get("items")).size())));
Be aware that since JMeter 3.1 it is recommended to use Groovy for any form of scripting as:
Groovy performance is much better
Groovy supports more modern Java features while with Beanshell you're stuck at Java 5 level
Groovy has a plenty of JDK enhancements, i.e. File.readLines() function
So kindly find Groovy solution below:
In the first Thread Group:
props.put('items', new File(vars.get('DataFolder') + '/items.txt').readLines()
In the second Thread Group:
def items = props.get('items')
def randomLine = items.get(new Random().nextInt(items.size))
I'm writing a generator and I need to get mock a Rails.application object and get back the Rails.application.class.parent as the name of the Rails application.
def test_model_with_application_namespace
name = "Dummyapp"
application = Rails.stubs(:application).class.parent.returns(name)
run_generator ["file", "--namespaced"]
assert_file "app/models/myapp/file.rb", /class Dummyapp::File < ActiveRecord::Base/
end
This is what I have so far for my test.
You need the object retured by Rails.application.class to be a mock that responds to parent and returns name. Right now, you just stub out application. You need parent, class, and application to be mocks. There is probably a cleaner way of doing it, but I think this will do what you want:
application = Rails.stubs(:application).returns(mock(:class => mock(:parent => name)))
I need to test a method belonging to a service class. This service class has several dependencies in the constructor, some used by this method, some not. If we should not be using a DI container for our unit tests what is the best way to instantiate the service class?
var service = new ServiceClass(new Repository1(), new Repository2(), new ServiceClass2(), etc.);
That's hard to read and seems like a lot of code just to test one method. Things get real messy when some of those dependencies have dependencies of their own.
You should really look at using a mocking framework to isolate your test from the actual dependent objects. I'm assuming you use C# (from the var keyword), so I'll give an example from RhinoMock.
var respository1 = MockRepository.GenerateMock<Repository1>();
repository1.Expect( r => r.SomeMethod() ).Return( someValue );
var repository2 = MockRepository.GenerateMock<Repository2>();
repository2.Expect( r => r.Method2() ).Return( someValue );
...
var service = new Service( repository1, repository2, ... );
repository1.VerifyAllExpectations();
repository2.VerifyAllExpectations();
Using this mechanism you can control how the mock object responds to your class under test and you isolate your test code from related dependencies. You can also test that your class under test is interacting properly with the classes that it depends on by verifying that the expectations that you set up have been met (called).
As for the number of parameters in the constructor, consider providing a default constructor that takes no parameters and having public settors for the dependencies. Then you can use the convenience mechanisms in C# 3.0 for defining them.
var service = new Service {
Repository1 = repository1,
Repository2 = repository2,
...
};
http://www.myjavatools.com/cuecards/refactoring.html
Constructor → Factory Method
if you want more than simple construction
Sometimes (especially if it is testing code) a bit of code reformatting can do the trick. While
var service = new ServiceClass(new Repository1(), new Repository2(), new ServiceClass2());
is definitely hard to read, this:
var service = new ServiceClass(
new Repository1(),
new Repository2(),
new ServiceClass2()
);
seems a bit better (at least to me).