Can I create gocql mocks for testing using https://github.com/golang/mock. If so, can someone please provide an example.
Are there better ways to generically mock all DBs the same generic way using interfaces?
Related
I have looked at code base of jdbi v3 but still can't figure out a way to mock Stream<JoinRow> returned by Dao class.
Constructor is package protected which is only invoked from JoinRowMapper's specialize function which itself needs StatementContext.
Is there any way to mock JoinRow object for unit testing purposes?
Thanks in advance.
Not clear, why you need to mock Stream<JoinRow>. But if you can't mock it, you can spy it :) Just, use Mockito Spy, or Spring #SpyBean depending on your context.
However, Jdbi has pretty good support for testing without mocking anything - just by using embedded DB (like H2) and JdbiRule.
Also, there are good examples of Jdbi tests in their Git repo. Specifically for Stream.
Hopefully, this answer clarifies something.
I want to know what Mockito is.
Is it supporting JUnit or is it an environment for writing JUnit test cases?
Can someone please explain to me the differences between JUnit and Mockito?
JUnit is a framework that helps with writing and running your unit tests.
Mockito (or any other mocking tool) is a framework that you specifically use to efficiently write certain kind of tests. At its core, any mocking framework allows you to omit instantiating "real" objects of production classes, instead the mocking framework creates a stub for you. Doing so gives you full control over that mocked object and enables you to verify the interactions taking place, for example.
Having said that, one core aspect in unit testing is the fact that you want to isolate your "class under test" from anything else in the world. In order to do that, you very often have to create "test doubles" that you provide to an object of your "class under test". You could create all those "test doubles" manually; or you use a mocking framework that generates object of a certain class for you using reflection techniques. Interestingly enough, some people advocate to never use mocking frameworks, but honestly I can't imagine doing that.
In other words, you can definitely use JUnit without using a mocking framework. Same is true for the reverse direction, but in reality, there are not many good reasons why you would want to use Mockito for anything else but unit testing.
JUnit is the Java library used to write tests (offers support for running tests and different extra helpers - like setup and teardown methods, test sets etc.).
Mockito is a library that enables writing tests using the mocking approach.
See here a nice article on the mocking vs non mocking tests: http://martinfowler.com/articles/mocksArentStubs.html
Layman's Explanation with Example
JUnit is used to test APIs in source code. To test APIs in JUnit, sometimes we may require data classes. To create those, we can use mockito.
Mock refers to creating duplicate or dummy objects.
We might be using many data classes in the project. For example, think of a Student object. It might have some 10 parameters like id, age, marks, gender etc. But you have one API to return a list of students whose age is greater than 10. So, to test this API we need to create student objects with all 10 parameters right. It is difficult. So, we can mock objects only with the required parameters. In our scenario, we will mock student objects with only age as a parameter.
Student student1=mock(Student.class);
when(student1.getAge()).thenReturn(20);
Student student2=mock(Student.class);
when(student2.getAge()).thenReturn(8);
So,above 2 objects can be added to a list and can be passed to API to test if API returns students who has age greater than 10.
I'm relatively new to the testing part of rails. I've used unit testing in other languages. but with rails I have noticed those some examples using mocking to test controllers and others using factories, What is the best practise here?
Example using mocks: http://solnic.eu/2012/02/02/yes-you-should-write-controller-tests.html
Example using factories: http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html
In my research I've noticed this question:
Rails Model Testing - Mocking vs. Factories
Is the answer the same for controllers?
I am leaning towards mocking, mainly to speed things up and test in isolation, but I have seen comments that imply mocks cause tests to be brittle.
Mocks are best at letting you isolate your tests. If you're testing what messages your controller sends, which you probably are, there's no reason to send those messages to a real instantiated factory created object. You can send them to a mock.
Also if you look at the second example. Mostly what you're doing with factories is using them to generate a valid set of attributes to send to a POST or UPDATE request. Using attributes_for not the whole object anyway.
One of the really interesting things I found that struggling with this kind of question about controller testing did for me, was highlight how the traditional way we build and use our Rails controllers is sometimes flawed and encourages a lot of very non-OO practices.
An example of an alternative approach is here: https://www.youtube.com/watch?v=CGN4RFkhH2M
This would be very easily tested using mocks and following Sandi Metz's approach laid out in Practical Object Oriented Design in Ruby - and this talk: http://www.confreaks.com/videos/2452-railsconf2013-the-magic-tricks-of-testing
I include the two links as you appear to be keen to learn more on the topic.
I'm having a simple test design problem, which I would like to solve once and for all.
I'm pretty used to regular Java design pattern where there is some Manager interface (or facade) and a set of DAO interfaces. Concrete implementation of ManagerImpl is using concrete implementations of DaoImpl.
Right now I'm at the point of implementation, where I don't have a database connected to my project yet, so I guess this is a perfect time to write proper unit tests without DB :-)
I was able to mock some methods of my manager by using mockito, but since the Test Under Method (or so called System Under Test) is using DAO internally, I would have to mock the DAO as well. Unfortunately I cannot do that without setting concrete DAO implementation in my manager, like myManager.setMyDao(mockedDao), but now I would have to pull out this setMyDao method into interface, which of course breaks encapsulation and makes my clean and perfect interfaces look like garbage.
So the question is: How to mock DAO in tests while preserving clean Manager-Dao architecture?
You should unit test concrete implementations, i.e. ManagerImplTest, which will explicitly create ManagerImpl and therefore you have all setMyDao methods available for mocks. Your test will not know about Manager interface.
BTW, it is not always necessary to create interfaces for everything. In most cases only single implementation of managers and daos will exist. If there is no any other strong reason (e.g. Spring AOP proxies or dependency separations), I guess it's better don't create interfaces for everything in sake of simplicity.
You can get rid of set methods altogether and inject factory. This way no extra method is exposed (in fact, no extra method even exists) and problem disappears. Then in test you configure factory mock to return DAO mocks and from that point on it's plain and simple.
I'm curious as to what method people like to use for mocking and why. The two methods that I know of are using hard coded mock objects and a mocking framework. To demonstrate, I'll outline an example using C#.
Suppose we have an IEmployeeRepository interface with a method called GetEmployeeById.
public interface IEmployeeRepository
{
Employee GetEmployeeById(long id);
}
We can easily create a mock of this:
public class MockEmployeeRepository : IEmployeeRepository
{
public Employee GetEmployeeById(long id)
{
Employee employee = new Employee();
employee.FirstName = "First";
employee.LastName = "Last";
...
return employee;
}
}
Then, in our tests we can explicitly tell our services to use the MockEmployeeRepository, either using a setter or dependency injection. I'm new to mocking frameworks so I'm curious as to why we use them, if we can just do the above?
That's not a Mock, it's a Stub. For stubbing, your example is perfectly acceptable.
From Martin Fowler:
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
When you're mocking something, you usually call a "Verify" method.
Look at this for the diff between Mocks and Stubs
http://martinfowler.com/articles/mocksArentStubs.html
I think the choice between writing dummy objects by hand or by using a framework depends a lot upon the types of components that you are testing.
If it is part of the contract for the component under test to communicate with its collaborators following a precise protocol, then instrumented dummy objects ("Mocks") are just the thing to use. It is frequently much easier to test such protocols using a mocking framework than by hand-coding. Consider a component that is required to open a repository, perform some reads and writes in a prescribed order, and then close the repository -- even in the face of an exception. A mocking framework would make it easier to set up all of the necessary tests. Applications related to telecommunications and process control (to pick a couple of random examples) are full of components that need to be tested in this fashion.
On the other hand, many components in general business applications have no particular constraints on how they communicate with their collaborators. Consider a component that performs some kind of analysis of, say, university course loads. The component needs to retrieve instructor, student and course information from a repository. But it does not matter what order it retrieves the data: instructor-student-course, student-course-instructor, all-at-once, or whatever. There is no need to test for and enforce a data access pattern. Indeed, it would likely be harmful to test that pattern as it would be demanding a particular implementation unnecessarily. In this context, simple uninstrumented dummy objects ("Stubs") are adequate and a mocking framework is probably overkill.
I should point out that even when stubbing, a framework can still make your life a lot easier. One doesn't always have the luxury of dictating the signatures of one's collaborators. Imagine unit-testing a component that is required to process data retrieved from a thick interface like IDataReader or ResultSet. Hand-stubbing such interfaces is unpleasant at best -- especially if the component under test only actually uses three of the umpteen methods in the interface.
For me, the projects that have required mocking frameworks were almost invariably of a systems-programming nature (e.g. database or web infrastructure projects, or low-level plumbing in a business application). For applications-programming projects, my experience has been that there were few mocks in sight.
Given that we always strive to hide the messy low-level infrastructure details as much as possible, it would seem that we should aim to have the simple stubs far outnumber the mocks.
Some distinguish between mocks and stubs. A mock object may verify that it has been interacted with in the expected way. A mocking framework can make it easy to generate mocks and stubs.
In your example, you've stubbed out a single method in an interface. Consider an interface with n methods, where n can change over time. A hand-stubbed implementation may require more code and more maintenance.
A mocked interface can have different outputs per test - One test you may have a method return null, another test has the method return an object, another test has the method throw an exception. This is all configured in the unit test, whereas your version would require several hand-written objects.
Psuedocode:
//Unit Test One
MockObject.Expect(m => m.GetData()).Return(null);
//Unit Test Two
MockObject.Expect(m => m.GetData()).Return(new MyClass());
//Unit Test Three
MockObject.Expect(m => m.GetData()).ThrowException();
I tend to write stubs and mocks by hand, first. Then if it can be easily expressed using a mock object framework, I rewrite it so that I have less code to maintain.
I have been writing them by hand. I was having trouble using Moq, but then I read TDD: Introduction to Moq, and I think I get what they say about classical vs. mockist approaches now. I'll be giving Moq another try this evening, and I think understanding the "mockist" approach will give me what I need to make Moq work better for me.