How do you mock your repositories? - testing

I've use Moq to mock my repositories. However, someone recently said that they prefer to create hard-coded test implementations of their repository interfaces.
What are the pros and cons of each approach?
Edit: clarified meaning of repository with link to Fowler.

I generally see two scenarios with repositories. I ask for something, and I get it, or I ask for something, and it isn't there.
If you are mocking your repository, that means you system under test (SUT) is something that is using your repository. So you generally want to test that your SUT behaves correctly when it is given an object from the repository. And you also want to test that it handles the situation properly when you expect to get something back and don't, or aren't sure if you are going to get something back.
Hard-coded test doubles are ok if you are doing integration testing. Say, you want to save an object, and then get it back. But this is testing the interaction of two objects together, not just the behavior of the SUT. They are two different things. If you start coding fake repositories, you need unit tests for those as well, otherwise you end up basing the success and failure of your code on untested code.
That's my opinion on Mocking vs. Test Doubles.

SCNR:
"You call yourself a repository? I've seen matchboxes with more capacity!"

I assume that by "repository" you mean a DAO; if not then this answer won't apply.
Lately I've been making "in memory" "mock" (or test) implementations of my DAO, that basically operate off of data (a List, Map, etc.) passed into the mock's constructor. This way the unit test class is free to throw in whatever data it needs for the test, can change it, etc., without forcing all unit tests operating on the "in memory" DAO to be coded to use the same test data.
One plus that I see in this approach is that if I have a dozen unit tests that need to use the same DAO for their test (to inject into the class under test, for example), I don't need to remember all of the details of the test data each time (as you would if the "mock" was hardcoded) - the unit test creates the test data itself. On the downside, this means each unit test has to spend a few lines creating and wiring up it's test data; but that's a small downside to me.
A code example:
public interface UserDao {
User getUser(int userid);
User getUser(String login);
}
public class InMemoryUserDao implements UserDao {
private List users;
public InMemoryUserDao(List users) {
this.users = users;
}
public User getUser(int userid) {
for (Iterator it = users.iterator(); it.hasNext();) {
User user = (User) it.next();
if (userid == user.getId()) {
return user;
}
}
return null;
}
public User getUser(String login) {
for (Iterator it = users.iterator(); it.hasNext();) {
User user = (User) it.next();
if (login.equals(user.getLogin())) {
return user;
}
}
return null;
}
}

Related

Is it possible to expect dispatch command from a non axon-class in AxonFramework

Suppose I have some classes which is not axon class (etc. Saga or agrgregate), and if I want it to dispatch command I could use command gateway, but here is the problem. I want to write
unit testing to make sure that this non axon-class has dispatched command already. So if it's either saga or aggregate I could use fixture and then given command or event, but is it possible to use fixture with these non axon-class also.
Here is how the code looks like
class MyService {
//...
lateinit var commandGateway: CommandGateway
fun doSomething(command: doSomethingCommand){
commandGateway.send(command)
}
}
class MyServiceTest {
//...
#Test
fun doSomething_ShouldDispatchDoSomethingCommand(){
// expect dispatch command from non axon-class
}
}
As you've noticed, Axon Framework provides Test Fixtures for Aggregates and Sagas, without specifying any additional options on the matter. The AggregateTestFixture does provide one method along the lines you are for, which is the AggregateTestFixture#registerAnnotatedCommandHandler. However, this is there to validate a component containing #CommandHandler annotated methods, not to validate dispatching.
Thus I think the most straightforward approach would be to mock or spy the CommandGateway/CommandBus to do the validation on to be honest.

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']);
}

TestNG - run tests in order impossible scenario?

I've tried many ways with no success and I'm starting to believe this is not achievable in TestNG and I just like to confirm with you.
I have web service I'm testing and I need to run few basic scenarios.
My current test methods, each with #Test annotation (each need to be testable as a single test):
dbResetTest
clearCacheTest
openURLTest
loginTest
actionXTest
actionYTest
I also need to run these scenarios consisting from above tests run IN ORDER:
Test login feature (openURLTest -> dbResetTest -> clearCacheTest -> loginTest)
Test X after login (openURLTest -> dbResetTest -> clearCacheTest -> loginTest -> actionXTest)
Test Y after clearing cache (clearCacheTest -> actionYTest)
The issue is, if I made tests from point 1 & 2 dependant on others I won't be able to run scenario 3 because clearCacheTest does not depend on any other in this particular scenario. I've tried running those test in order through xml and by using dependencies but with no success.
Of course I could make actionYTest to call clearCacheTest directly but then if clearCacheTest fails the report will show that actionYTest was the failing one which is what I try to avoid.
I'm pretty sure now what I need is not achievable in TestNG but maybe I'm wrong...
I think you should change your tactics slightly. Instead of perceiving these ~(dbResetTest, etc.) as test Classes you should make them test methods instead and use dependsOnMethods programatically (not from XML) instead of dependsOnGroups. Then you will be able to implement your required logic rather easily (every test is unique --> #Test annotation, every test is executed in certain priority --> use priority parameter). Then the 1,2,3 tests should be your test classes. So here it is how you do it:
public class LoginFeature {
#Test (priority=1)
public openURLTest(){
}
#Test (priority=2, dependsOnMethods="openURLTest")
public dbResetTest (){
}
#Test (priority=3, dependsOnMethods="dbResetTest")
public clearCacheTest (){
}
#Test (priority=4, dependsOnMethods="clearCacheTest" )
public loginTest(){
}
}
This way if something fails in between your tests the rest of scenarios will automatically be skipped and you won't need to call directly clearCacheTest.
Hope this helps!
Update
After OP's comment
Well again I think you kinda have of a design issue. For your methods to be called multiple times they need to sit somewhere that they are accessible. You are almost there with your approach but not quite. So here is how you can call the methods; multiple times and run them every time from scratch (I'll show you the code first and then explain in detail):
parent class
public class TestBase{
//include here all your important methods *without* #Test Annotation
public void dbReset(){
//perform db reset
}
public void clearCache(){
//clear browser cache
}
public boolean openURL(){
//try to open test URL
return didIreachTestURLSuccessfully;
}
}
child class
public class loginFeature extends TestBase{
#Test (priority=1)
public void attemptToResetDataBase(){
dbReset();
}
#Test (priority=2, dependsOnMeth0ds="attemptToResetDataBase")
public void clearCacheTest(){
clearCache();
}
#Test (priority=3, dependsOnMeth0ds="clearCacheTest")
public void verifySuccessfulLogin(){
login();
}
}
So, you include all of your test methods in a parent class, called TestBase. Then you create your test (loginTest for example) with a class that extends TestBase. Now you can call your methods multiple times, treat them each time as an individual test and connect them with dependencies according to your needs (i.e I have each one of them depending on the prior method; but you could rearrange them and put them all to depend on one, or to no-one).
Because your test class inherits from TestBase you don't even need to create an object to access the internal methods; you can call them directly instead.
Hope this solves it for you, do not hesitate to write a comment if you need more info.

SessionFactory - one factory for multiple databases

We have a situation where we have multiple databases with identical schema, but different data in each. We're creating a single session factory to handle this.
The problem is that we don't know which database we'll connect to until runtime, when we can provide that. But on startup to get the factory build, we need to connect to a database with that schema. We currently do this by creating the schema in an known location and using that, but we'd like to remove that requirement.
I haven't been able to find a way to create the session factory without specifying a connection. We don't expect to be able to use the OpenSession method with no parameters, and that's ok.
Any ideas?
Thanks
Andy
Either implement your own IConnectionProvider or pass your own connection to ISessionFactory.OpenSession(IDbConnection) (but read the method's comments about connection tracking)
The solution we came up with was to create a class which manages this for us. The class can use some information in the method call to do some routing logic to figure out where the database is, and then call OpenSession passing the connection string.
You could also use the great NuGet package from brady gaster for this. I made my own implementation from his NHQS package and it works very well.
You can find it here:
http://www.bradygaster.com/Tags/nhqs
good luck!
Came across this and thought Id add my solution for future readers which is basically what Mauricio Scheffer has suggested which encapsulates the 'switching' of CS and provides single point of management (I like this better than having to pass into each session call, less to 'miss' and go wrong).
I obtain the connecitonstring during authentication of the client and set on the context then, using the following IConnectinProvider implementation, set that value for the CS whenever a session is opened:
/// <summary>
/// Provides ability to switch connection strings of an NHibernate Session Factory (use same factory for multiple, dynamically specified, database connections)
/// </summary>
public class DynamicDriverConnectionProvider : DriverConnectionProvider, IConnectionProvider
{
protected override string ConnectionString
{
get
{
var cxnObj = IsWebContext ?
HttpContext.Current.Items["RequestConnectionString"]:
System.Runtime.Remoting.Messaging.CallContext.GetData("RequestConnectionString");
if (cxnObj != null)
return cxnObj.ToString();
//catch on app startup when there is not request connection string yet set
return base.ConnectionString;
}
}
private static bool IsWebContext
{
get { return (HttpContext.Current != null); }
}
}
Then wire it in during NHConfig:
var configuration = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005
.Provider<DynamicDriverConnectionProvider>() //Like so

Mocking a database connection

I'm trying to write some tests with PHPUnit for our various classes/methods/functions. Some of these require database connectivity. Obviously, I'd like to Mock these, so that I don't change our database(s).
Can someone point me to some code that explains how to do this? I see lots of examples of Mocking, but nothing specifically about mocking the database.
In general, you don't want to mock the database, or any other similar external dependency. It's better to wrap the database in your code with something else, and then you can mock the wrapper. Because a database might have many different ways that it can interact, whereas your code and your tests only care about one or two, your database wrapper only needs to implement those. That way mocking the wrapper should be quite simple.
You would also need some kind of integration test on the wrapper to check it's doing what it's supposed to, but there will only be a few of these tests so they won't slow your unit tests too much.
Mock of Database
I would write a wrapper around the calls to the Database in the application.
Example in Pseudo Code
CallDataBase (action, options,...) {
// Code for connectiong to DataBase
}
Then you just mock of that function just you would like any other function
CallDataBase (action, options,...) {
return true;
}
This way you can mock of the database without bothering about it being a webservice or a database connection or whatever. And you can have it return true or whatever.
Test how your system handles the database response
To take this idea one step further and make your tests even more powerful you could use some kind of test parameters or environment parameters to control what happens in the mocked off database method. Then you can successfully test how your codes handels different responses from the database.
Again in pseudo-code (assuming your database returns xml answer):
CallDataBase (action, options,...) {
if TEST_DATABASE_PARAMETER == CORRUPT_XML
return "<xml><</xmy>";
else if TEST_DATABASE_PARAMETER == TIME_OUT
return wait(5000);
else if TEST_DATABASE_PARAMETER == EMPTY_XML
return "";
else if TEST_DATABASE_PARAMETER == REALLY_LONG_XML_RESPONSE
return generate_xml_response(1000000);
}
And tests to match:
should_raise_error_on_empty_xml_response_from_database() {
TEST_DATABASE_PARAMETER = EMPTY_XML;
CallDataBase(action, option, ...);
assert_error_was_raised(EMPTY_DB_RESPONSE);
assert_written_in_log(EMPTY_DB_RESPONSE_LOG_MESSAGE);
}
...
And so on, you get the point.
Please note that all my examples are Negative test cases but this could of course be used to test Positive test cases also.
Good Luck