Writing tests for a Symfony2 service that uses the database - symfony

I'm creating a small bundle for Symfony2, which does nothing more than provide a service; it can be called to insert a line into the database, containing a few parameters:
class AuditLogService {
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function log($type, $channel, $message) {
$log = new AuditLog();
$log->setType($type);
$log->setChannel($channel);
$log->setMessage($message);
$this->em->persist($log);
$this->em->flush();
}
}
Now I need to write a test for it, so basically here are the steps I'm assuming I should take:
write a test that gets logger service, but uses a mock entityManager instead?
call function on that logger which uses the mocked em
try to fetch it back from the mocked em, using the parameters I used in step 2
assert if I find a result or not
I'm pretty sure that in theory these are the correct steps, but can anyone point me into the right direction as to how to actually do it?
I have this:
public function testServiceLoaded()
{
$this->assertEquals(get_class($this->container->get('bbit_audit_log.service')), 'BBIT\AuditLogBundle\Services\AuditLogService');
}
This comes back with the following error:
"bbit_audit_log.service" has a dependency on a non-existent service "doctrine.orm.entity_manager"
It seems like my container does not contain the entitymanager?

In unit test skip 3 and 4. It's not responsibility of AuditLogService to save in the database (but to call em). 3 and 4 should be tested by functional test.

Related

Assert function has been called once phpunit

I'm new to PHPUnit and i'm wondering how to assert that a function from a service has been called.
I tried to mock my service that implement the function ofDatetimeRange :
$mock = $this->getMockBuilder(QueryBuilder::class)
->onlyMethods(['ofDatetimeRange'])
->getMock();
And then just call the function that suppose to call the service and finally assert that have been call once or never.
Here is the test case :
/**
* Test that there is no date filter.
*
* #return void
*/
public function testNoDateFilter()
{
$mock = $this->getMockBuilder(QueryBuilder::class)
->onlyMethods(['ofDatetimeRange'])
->getMock();
$engine = new Engine();
$engine->prepareQuery(); <--- this should call QueryBuilder::ofDatetimeRange
$mock->expects($this->exactly(1))->method('ofDatetimeRange');
}
Expectation failed for method name is "ofDatetimeRange" when invoked 1
time(s). Method was expected to be called 1 times, actually called 0
times.
It looks like my engine doesn't use the mocked instance...
Is there something i'm doing wrong ?
Note that $engine->prepareQuery() should call ofDatetimeRange method of QueryBuilder class.
You're right, $engine object in your test doesn't use the mock object.
I'm not sure how exactly Engine class looks like, but to be able to use mock you usualy should design your class to have mocked object dependency.
class Engine
{
private QueryBuilder $qb;
public function __construct(QueryBuilder $qb)
{
$this->qb = $qb;
}
}
And then you pass the mock object in your test case:
$engine = new Engine($mock);
This should work.

How to Write a Mockito+Junit test case for a method which reads the properties from properties file

I have to write a Mockito+Junit test for a method and that method reads the data from a properties file. When I am trying to execute my test case the properties file is loading but it is returning null. Following is my code:
#RestController
#PropertySource("classpath:/com/example/prop.properties")
public class ReadProp {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#RequestMapping(value="/")
public void getDetails(){
System.out.println(name);
System.out.println(rollNo);
}
}
The test case is as follows
#RunWith(MockitoJUnitRunner.class)
#PropertySource("classpath:/com/example/prop.properties")
public class ReadPropTest {
#Mock
private ReadProp readProp;
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#Test
public void readValues() {
System.out.println(name);
System.out.println(rollNo);
readProp.getDetails();
}
}
Let's start at the beginning... Your test has many problems, the first being that you don't actually have anything to test...
#Mock
private ReadProp readProp;
This, together with #RunWith(MockitoJUnitRunner.class) makes your readProp object a mock object. A mock object contains no logic. It has nothing to do with your original ReadProp class except the method names, etc. But the method themselves don't actually DO anything (unless you tell them to).
So, first problem: You are not test YOUR RealProp class, but a mock object, which doesn't help. You are creating something that only looks like a RealProp object and then you test that, but of course, that doesn't tell you anything. Mocks are there to help you simplify dependencies, etc. in your test - but it makes no sense to actually test the mock.
So, don't. Instead, make a real RealProp.
Another problem is, that System.out is not very good to test, but I assume that's just temporary code, so let's ignore that for a moment...
The next question is, what do you want to test. There are two possibilities:
a) You want to test that, under the assumption that the fields name and rollNo were filled correctly by whatever dependency injection framework (spring, in this case) you are using, the method getDetails will use them correctly.
b) You want to test that the injection of the values works and also the method getDetails uses that values.
These are two different tests. a) would be a true unit test, since it's limited to this "unit". b) would be more complex, since it doesn't just look at this unit, but also at the Spring environment around it. I would not go so far to call it an integration test, but it's more than a simple unit test.
Personally, I try to avoid the Spring environment in my unit tests as far as possible and concentrate on my own code, testing the Spring integration later in real integration tests, but that's as much personal preference as anything else.
Let's start with a)...
public class ReadPropTest {
private ReadProp readProp = new ReadProp();
#Before
public void init() {
Whitebox.setInternalState(readProp, "name", "someName");
Whitebox.setInternalState(readProp, "rollNo", "someRollNo");
}
#Test
public void myTest() {
...
}
}
Of course, you can also use Spring's ReflectionTestUtils instead of Mockito's Whitebox, doesn't matter.
And for b), you could try something like this. Of course you migth have to play around with the Configuration a bit, as it depends on your setup.
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = {"classpath:applicationContext-spring.xml" })
public class ReadPropTest {
#Autowired
private ReadProp readProp;
...
}

PHPUnit test if class methods were called

I have model class that calls mailer class inside one of its methods:
class someModel{
public function sendEmail($data){
$mailer = new Mailer();
$mailer->setFrom($data['from']);
$mailer->setTo($data['to']);
$mailer->setSubject($data['subject']);
return $mailer->send();
}
}
How can I test sendEmail method? Maybe I should mock mailer class and check if all these mailer methods were called in sendMail method?
Your help would be appreciated.
IMO wrapping the Mailer class does not solve the problem you're facing, which is you don't have control over the Mail instance being used.
The problem comes from creating the dependencies inside the object that needs them instead of injecting them externally like this:
class someModel{
private $mailer;
public function __construct(Mailer $mailer) {
$this->mailer = $mailer;
}
public function sendEmail($data){
$this->mailer->setFrom($data['from']);
$this->mailer->setTo($data['to']);
$this->mailer->setSubject($data['subject']);
return $this->mailer->send();
}
}
When creating the someModel instance, you must pass a Mail instance (which is an external dependency). And in the test you can pass a Mail mock that will check that the correct calls are being made.
Alternative:
If you feel that injecting a Mail instance is bad (maybe because there are lots of someModel instances), or you just can't change your code this way, then you could use a Services repository, that will keep a single Mail instance and that allows you to set it externally (again, in the test you would set a mock).
Try a simple one like Pimple.
I would (and have in my own code with Mailer!) wrap your instance of Mailer inside a class that you write. In other words, make your own Email class that uses Mailer under the hood. That allows you to simplify the interface of Mailer down to just what you need and more easily mock it. It also gives you the ability to replace Mailer seamlessly at a later date.
The most important thing to keep in mind when you wrap classes to hide external dependencies is keep the wrapper class simple. It's only purpose is to let you swap out the Email libraries class, not provide any complicated logic.
Example:
class Emailer {
private $mailer = new Mailer();
public function send($to, $from, $subject, $data) {
$this->mailer->setFrom($from);
$this->mailer->setTo($to);
...
return $mailer->send();
}
}
class EmailerMock extends Emailer {
public function send($to, $from, $subject, $data) {
... Store whatever test data you want to verify ...
}
//Accessors for testing the right data was sent in your unit test
public function getTo() { ... }
...
}
I follow the same pattern for all classes/libraries that want to touch things external to my software. Other good candidates are database connections, web services connections, cache connections, etc.
EDIT:
gontrollez raised a good point in his answer about dependency injection. I failed to explicitly mention it, but after creating the wrapper the way you would want to use some form of dependency injection to get it into the code where you want to use it. Passing in the instance makes it possible to setup the test case with a Mocked instance.
One method of doing this is passing in the instance to the constructor as gontrollez recommends. There are a lot of cases where that is the best way to do it. However, for "external services" that I am mocking I found that method became tedious because so many classes ended up needing the instance passed in. Consider for example a database driver that you want to Mock for your tests, but you use in many many different classes. So instead what I do is create a singleton class with a method that lets me mock the whole thing at once. Any client code can then just use the singleton to get access to a service without knowing that it was mocked. It looked something like this:
class Externals {
static private $instance = null;
private $db = null;
private $email = null;
...
private function __construct() {
$this->db = new RealDB();
$this->mail = new RealMail();
}
static function initTest() {
self::get(); //Ensure instance created
$db = new MockDB();
$email = new MockEmail();
}
static function get() {
if(!self::$instance)
self::$instance = new Externals();
return self::$instance;
}
function getDB() { return $this->db; }
function getMail() { return $this->mail; }
....
}
Then you can use phpunit's bootstrap file feature to call Externals::initTest() and all your tests will be setup with the mocked externals!
First, as RyanW says, you should write your own wrapper for Mailer.
Second, to test it, use a mock:
<?php
class someModelTest extends \PHPUnit_Framework_TestCase
{
public function testSendEmail()
{
// Mock the class so we can verify that the methods are called
$model = $this->getMock('someModel', array('setFrom', 'setTo', 'setSubject', 'send'));
$controller->expects($this->once())
->method('setFrom');
$controller->expects($this->once())
->method('setTo');
$controller->expects($this->once())
->method('setSubject');
$controller->expects($this->once())
->method('send');
$model->sendEmail();
}
}
The above code is untested, but it basically mocks the someModel class, creating dummy functions for each each function called within sendEmail. It then tests to make sure each of the functions called by sendEmail is called exactly once when sendEmail is called.
See the PHPUnit docs for more info on mocking.

In phpunit what is the difference between __construct versus setup?

I am curious to know it is good practice to create object in test class __construct or we should always use setup/teardown approach ( or setUpBeforeClass/tearDownAfterClass approach)?
I aware of the fact set/teardown gets called for each test so will it do any good if I put my object creation code in it? e.g.
//mytestclass.php
class MyTestClass extends PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new FooClass();
}
public testFooObj()
{
//assertions for $this->obj
}
...
}
what could be the issues if I create object in constructor like this:
class MyTestClass extends PHPUnit_Framework_TestCase
{
private $obj;
protected function __construct()
{
$this->obj = new FooClass();
}
public testFooObj()
{
//assertions for $this->obj
}
...
}
I tried googling around as well as PHPUnit documentation couldn't get much information about, Can you please help me to understand which one is good practice?
setUp() gets called before each of your tests is ran. __construct() happens when your class is instantiated. So if you have multiple tests and they use local properties and modify them, using setUp() you can ensure that they are the same before each test is ran. The opposite of setUp() is tearDown() where you can ensure that test data gets cleaned up after each test.
As I have just found out, implementing the default class constructor instead of the setupBeforeClass() method breaks the #dataProvider annotations (probably all kinds of annotations), yielding a "Missing argument" exception for any parameterized tests.
Missing argument 1 for AppBundle\Tests\Service\InvitationVerifierTest::testDireccionInvalida()
Replacing public function __construct() for public static function setUpBeforeClass() gets rid of the exception. So there it goes, favor the setupBeforeClass() method over the regular constructor.
PHPUnit version 4.5.0

unit testing a class that uses linq to sql

I want to write unit test for a class that contains linq to sql codes . I mean inside each method I have created a new DbContext and done database jobs .
I searched the web . first I came to use repository and Unit of Work patterns but I figured out that DbContext itself is a unit of work and its dbset works as repositories . another point is that I think there is no need to test Linq part because it works as it should ( tested by .net team ) . I want to test the logic I have added to the code . so I decided to create an interface with necessary methods with two implementations , one uses linqToSql while another is just a mock . something like this :
public interface IDbManager
{
bool Insert(MyEntity newEntity);
}
public class RealDbManager:IDbManager
{
public bool Insert(MyEntity newEntity)
{
using (DbDataContext db = new DbDataContext())
{
db.MyEntities.InsertOnSubmit(newEntity);
db.SubmitChanges();
}
}
}
public class MockDbManager:IDbManager
{
public bool Insert(MyEntity newEntity)
{
return true;
}
}
is the whole idea correct ? if so is this a correct implementation ?
is it possible to define DbDataContext as a class variable instead of creating new instance inside each method ?
You have the right general idea for a start. Your Mock Insert method should save the entity to some in-memory store so that subsequent queries will return the inserted information, as would be expected. But the very basic idea of having an interface, with a 'real' and a 'mock' implementation is there.
Remember that when using your Mock in tests, you are testing your other code that uses the mock - not the mock itself.
As for defining the DataContext as a member variable; you could use an IDisposable pattern for it, like so:
public class RealDbManager:IDbManager, IDisposable
{
DbDataContext db = new DbDataContext();
public bool Insert(MyEntity newEntity)
{
{
db.MyEntities.InsertOnSubmit(newEntity);
db.SubmitChanges();
}
}
public void Dispose()
{
db.Dispose();
}
}
You would just have to be sure to dispose of your DbManager, then.
Yes. The only thing I would avoid is to create an actual mocked class (in this case it should be called Fake), but using a mocking engine.
In your question you mention two kind of tests. First is testing the behavior of your class, the second is testing the integration of it. They seem the same but it's not.
In the first you need to mock your class to test its 'connection' against your other classes this way (using Moq):
[Test]
public void Test()
{
var entity = new Entity();
var mocked = new Mock<IDbManager>();
//you are telling the moq engine everytimes it finds an invocation of your repository
//to return true as you did in you mocked class
mocked.Setup( x => x.Insert( entity ) ).Returns( true );
var classUnderTest = new ClassUnderTest( mocked.Object );
//in this method you invoke your repository
var ret = classUnderTest.DoSomething( entity );
//assertions
Assert.Equal( something, ret);
//eventually you can verify that your repository has been hit once
mocked.Verify( x => x.Insert( It.IsAny<Entity>), Times.Once);
}
in the later as you correctly state, you have nothing to test on linq (Microsoft did it for us), but in case you need to verify the correctness of your linq you can do it only against a real db (or using a repository pattern against a fake repository). This is an integration test and it's has nothing to share with mocking.
To decouple your class from DbContext you could use repository pattern. Have a look at this article. http://dotnetspeak.com/index.php/2011/03/repository-pattern-with-entity-framework/

Resources