Difference in Behavior between Rhino and FakeItEasy - rhino-mocks

We're considering switching from Rhino to FakeItEasy for our mocking framework. The main reason is simplicity, in FakeItEasy there's only one way to do things. Rhino has record/playback, AAA, stub, partial mock, strict mock, dynamic mock, etc.
I'm rewriting some of our tests using FakeItEasy to ensure it will do everything Rhino is currently doing for us, and I've encountered something I can't explain and was hoping someone could enlighten me.
In Rhino, I have the following test. The code has been abbreviated.
ConfigurationManagerBase configManager = _mocks.Stub<ConfigurationManagerBase>();
using( _mocks.Record() )
{
SetupResult
.For( configManager.AppSettings["ServerVersion"] )
.Return( "foo" );
}
The unit test to which this code is attached runs just fine and the test passes. I rewrote it using FakeItEasy as follows.
ConfigurationManagerBase configManager = A.Fake<ConfigurationManagerBase>();
A.CallTo( () => configManager.AppSettings["ServerVersion"] )
.Returns( "foo" );
Now when I run the test it fails, but it's because FakeItEasy is throwing an exception.
The current proxy generator can not intercept the specified method for the following reason:
- Non virtual methods can not be intercepted.
That seemed odd, because Rhino has the same restriction. What we think is happening in that while AppSettings is virtual on ConfigurationManagerBase, the indexer property is not. We corrected the problem by changing the FakeItEasy test to read.
NameValueCollection collection = new NameValueCollection();
collection.Add( "ServerVersion", "foo" );
A.CallTo( () => configManager.AppSettings )
.Returns( collection );
I'm basically just trying to understand whether I'm doing something wrong with FakeItEasy or is Rhino performing some "magic" behind the scenes with that indexer?

The following configuration should be similar to what Rhino does if this doesn't work Rhino does something magic:
NextCall.To(configManager.AppSettings).Returns("foo");
var ignored = configManager.AppSettings["ServerVersion"];

Related

How can I mock a call to Spring's repository `saveAll()` method using mockk?

I am using Mockk as my mocking framework when testing my Spring Boot Data repository interfaces.
Actually I am doing the following
every { itemRepository.saveAll(listOf(any(), any())) } returns listOf<Item>(mockk())
which should mock the following behaviour
val loot: List<Item> = itemGenerator.generateLoot(lootTable)
itemRepository.saveAll(loot)
The error message I receive is the following:
Failed matching mocking signature for
SignedCall(retValue=, isRetValueMock=true, retType=class kotlin.collections.Iterable, self=ItemRepository(#28), method=saveAll(Iterable), args=[[com.barbarus.gameserver.item.Item#ea00de, com.barbarus.gameserver.item.Item#23ca36d]], invocationStr=ItemRepository(#28).saveAll([com.barbarus.gameserver.item.Item#ea00de, com.barbarus.gameserver.item.Item#23ca36d]))
left matchers: [any(), any()]
The error message says left matchers: [any(), any()] pointing out that I somehow am not defining the expected arguments right.
I could fully define the items by real implementations in my test logic but I'd like to stick with mockk() just to keep the test code slim and fast.
However I kinda am not able to define the List<Item> with two elements using listOf(any(),any()) here. I tried other API of Mockk without any luck.
Any idea what to use in this case?
You should type the any() when you are passing into saveAll().
For instance:
import com.barbarus.gameserver.item.Item
...
every { itemRepository.saveAll(any<List<Item>>() } returns listOf<Item>(mockk())
Solution from another post

The method expect(boolean) is undefined for the type in Shiro test

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.

How to Mock private variable in Grails in spock framework

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.

Lumen - seeder in Unit tests

I'm trying to implement unit tests in my company's project, and I'm running into some weird trouble trying to use a separate set of data in my database.
As I want tests to be performed in a confined environment, I'm looking for the easiest way to input data in a dedicated database. Long story short, to this extent, I decided to use a MySQL dump of inserted data.
This is basically my seeder code:
public function run()
{
\Illuminate\Support\Facades\DB::unprepared(file_get_contents(__DIR__ . '/data1.sql'));
}
Now here's the problem.
In my unit test, I can call the seeder, but :
If I call the seeder in the setUpBeforeClass(), it works. Although it doesn't fit my needs as I want to be able to invoke different sets of data for different tests
If I call the seeder within a test, the data is never inserted in the database (either with or without the transaction trait).
If I use DB::insert instead of ::raw or ::unprepared or ::statement without using a raw sql file, it works. But my inserts are too complicated for that.
Here's a few things I tried with the same results :
DB::raw(file_get_contents(__DIR__.'/database/data1.sql'));
DB::statement(file_get_contents(__DIR__ . '/database/data1.sql'));
$seeder = new CheckTestSeeder();
$seeder->run();
\Illuminate\Support\Facades\Artisan::call('db:seed', ['--class' => 'CheckTestSeeder']);
$this->seeInDatabase('jackpot.progressive', [
'name_progressive' => 'aaa'
]);
Any pointers on how to proceed and why I have different behaviors if I do that in the setUpBeforeClass() and within the test would be appreciated!
You may use Illuminate\Foundation\Testing\RefreshDatabase trait as explained here. If you need something more, you can override refreshTestDatabase method in RefreshDatabase trait.
protected function refreshTestDatabase()
{
parent::refreshTestDatabase();
\Illuminate\Support\Facades\Artisan::call('db:seed', ['--class' => 'CheckTestSeeder']);
}

Instantiate A Class For Testing

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).