Rectangle 27 22

Mockito was developed to allow BDD-style unit testing, that is:

  • Given (the context in which your unit-test runs)
  • When (the events producing the behaviour you're interested in)

as opposed to

  • Expect (here's where the verification gets done)
  • Then (go back and look at what you wrote in the Expect because there's no actual info here).

IMHO it produces more readable tests, and allows you to separate things like the context in which you're running (setting up the Mocks) and verification of the behaviour you're interested in. Previous mocking frameworks required you to set up expectations for every interaction, regardless of whether it was relevant to the aspect of behaviour you were looking at in that test or not.

that's not true, you don't have to 'set up expectations for every interaction'. With Easymock you can just setup a NiceMock (createNiceMock()). Anyway I think that testing object interaction is a good idea (and should be the default/common behaviour).. I seldom use niceMocks

Mockito was originally a fork of EasyMock, before NiceMock existed. In BDD, they're not tests - just descriptions of behaviour with some examples of how to use a class. The idea of BDD is to make it easy and safe to change, rather than pinning the code down so it doesn't break. Tests are a nice by-product. In that world, testing every interaction doesn't make as much sense as producing readable, easy-to-change examples.

I want to test my code.. then if it's readable and easy to change it is another story.. I don't think TDD Experts would confirm that 'interaction doesn't make much sense'. You always produce something from the interaction of components... I rather prefer to have something that is less readable but test the correct interactions .. IMHO interaction (as readable / easy-to-change code) is a main subject in Testing and shouldn't be avoided so easily

I don't think TDD experts are necessarily BDD experts. I also never said "interaction doesn't make much sense" - please read the wording I actually used and consider the context.

I really like the definition of xunitpatterns.com/Test%20Double.html, which makes the test-aspect very clear. I use Mockito for Test-Stubs, Test-Mocks and Test-Spy. I go the middle/pragmatic way writing tests, they should be easy to write but also should test "something" (to avoid 'false negative' test results). Sure easymock (when not using nice-mocks) is more strict and theoratically more correct but it created a lot of confusing test-cases. in my view inside test-cases the verify step should be the last and not be mixed with the setup (like 'expect' in easymock).

java - Mockito preferrable over EasyMock? - Stack Overflow

java unit-testing mocking easymock mockito
Rectangle 27 10

I give you an explanation that other people probably wont like, but I (and a lot of people I mentioned it to) find/found very helpful: Powermock is the mocking framework ... that you better not use.

The main advantage from Powermock is that you can use it to test certain constructs (for example static method invocations) that EasyMock can't mock. Thus: when you want to test 3rd party code that you can't change; and that contains static calls; then you might turn to PowerMock.

But when you write your own code, and you focus on writing testable code; then you will find that the "need to use Powermock" is absolutely equal to "you did a bad job designing your code". Using static for example directly leads to direct coupling between your classes; and therefore it is hard to get rid of it once it is in.

On EasyMock / Mokito: mainly "two different ways" of writing down testcases; the later one leading to tests that many people find easier to read; whereas EasyMock and "strict" mocks allow for writing down test cases that will break quickly upon most changes in your production code (which by itself can be very useful, or very annoying).

This is indeed a very good advice. Thanks for sharing your opinion!

You are very welcome ;-)

Great suggestion. Thanks a lot !

junit - What is the difference between PowerMock, EasyMock and Mockito...

junit mockito powermock easymock
Rectangle 27 20

It seems the order of the definitions in the xml actually matter when using factories to create beans with autowiring. If you place the declaration of someInterfaceMock above component-scan it will work.

Some clarification why: When Spring tries to autowire SomeClass it searches for a bean of type SomeDependency. At this stage someInterfaceMock is still a factory so Spring checks the signature of the factory method EasyMock.createMock(...) which returns <T> so Spring only finds an Object which isn't the type required.

A better way would be to use Spring's FactoryBean interface to create your mocks.

Here is a basic implementation that should work:

public class EasyMockFactoryBean<T> implements FactoryBean<T> {
    private Class<T> mockedClass;

    public void setMockedClass(Class mockedClass) {
        this.mockedClass = mockedClass;
    } 

    public T getObject() throws Exception {
        return EasyMock.createMock(mockedClass);
    }

    public Class<T> getObjectType() {
        return mockedClass;
    }

    public boolean isSingleton() {
        return true;
    } 

}

Here is the bean definition (the order won't matter!):

<bean class="com.example.EasyMockFactoryBean">
    <property name="mockedClass" value="com.example.Dependancy"/>
</bean>

Thanks! The order did the trick, but I think that I will use the EasyMockFactoryBean implementation, considering that it is likely that I will have to mock other dependencies later.

java - Autowiring of beans generated by EasyMock factory-method? - Sta...

java spring easymock autowired factory-method
Rectangle 27 20

It seems the order of the definitions in the xml actually matter when using factories to create beans with autowiring. If you place the declaration of someInterfaceMock above component-scan it will work.

Some clarification why: When Spring tries to autowire SomeClass it searches for a bean of type SomeDependency. At this stage someInterfaceMock is still a factory so Spring checks the signature of the factory method EasyMock.createMock(...) which returns <T> so Spring only finds an Object which isn't the type required.

A better way would be to use Spring's FactoryBean interface to create your mocks.

Here is a basic implementation that should work:

public class EasyMockFactoryBean<T> implements FactoryBean<T> {
    private Class<T> mockedClass;

    public void setMockedClass(Class mockedClass) {
        this.mockedClass = mockedClass;
    } 

    public T getObject() throws Exception {
        return EasyMock.createMock(mockedClass);
    }

    public Class<T> getObjectType() {
        return mockedClass;
    }

    public boolean isSingleton() {
        return true;
    } 

}

Here is the bean definition (the order won't matter!):

<bean class="com.example.EasyMockFactoryBean">
    <property name="mockedClass" value="com.example.Dependancy"/>
</bean>

Thanks! The order did the trick, but I think that I will use the EasyMockFactoryBean implementation, considering that it is likely that I will have to mock other dependencies later.

java - Autowiring of beans generated by EasyMock factory-method? - Sta...

java spring easymock autowired factory-method
Rectangle 27 6

With easy mock, you don't need to wrap void functions around expect(). You just need to do something like:

obj = createMock(...)
obj.someVoidMethod();
replay(obj);
...
verify(obj);

java - Mocking void method with EasyMock and Mockito - Stack Overflow

java unit-testing mockito easymock
Rectangle 27 7

I'm more familiar with EasyMock than Mockito, so I had to do a little digging. Mockito has a page that does an explicit comparison from the Mockito point of view.

As I see it, the advantages of Mockito are:

  • Explicit separation of stub and verification
  • Matchers are based on Hamcrest (also supported by JUnit) instead of a custom API
  • Created mocks are always 'nice'; that is, method calls that are unmocked return clean data (like an empty list) instead of failing

EasyMock has a very similar function set. The core differentiators for Mockito are based on those areas of EasyMock that the Mockito team thought were limitations or sub-optimal practices.

From a functional point of view, neither product is able to mock static methods (I needed to do this for testing without an MBeanServer), but in that case you can use PowerMock on top of either framework.

I'd say go with whichever style fits your testing requirements.

java - Mockito preferrable over EasyMock? - Stack Overflow

java unit-testing mocking easymock mockito
Rectangle 27 6

Mockito may be better now than it was when I last tried it, but it lost me when it changed its API to be incompatible with previous versions. Upgrading to the latest version would have required me to change many of my existing unit tests, which I found unacceptable. I decided it was too immature and unstable for my needs.

That doesn't mean that there's anything wrong with it, though. The version I was using still works fine, although I've since switched back to EasyMock.

I can image this was painful. In my case I was starting off with version 1.8.3. Looking at the release-notes the API seems to have stabilized.

java - Mockito preferrable over EasyMock? - Stack Overflow

java unit-testing mocking easymock mockito
Rectangle 27 4

In mockito, if you want to check only that the DAO delete method is called with the correct parameter, then verify is what you want.

I would suggest that this is exactly what you want since your unit test for PersonManager should not be testing PersonDao.

java - Mocking void method with EasyMock and Mockito - Stack Overflow

java unit-testing mockito easymock
Rectangle 27 13

The simple answer is we do not need them.

Nor do we need other existing frameworks, but using Mocking frameworks makes our lives easier. As developers we can spend more time on the problem at hand, rather than creating or carrying out what mocking frameworks can do.

I was exactly the same. Why should I bother learning a mocking framework? Hand written stubs do fine.

A few points come to mind, mainly the fact that after a while your tests become obscure with test stubs. What you are refering to when using hand written stubs are known as test extensions. You extend code to enable what mocking frameworks do. In other words you write code to stub, or return values depending on what happens. This takes time, and effort. Not to mention space. A mocking framework can do all this in a matter of lines.

The benefits of a mocking framework are:

The biggest benefit comes to when you require mock objects. Having to hand write code to check if a method was called, how many times and so forth is a mini task in itself. If someone else has done so, and created a throughly tested, well documented framework, it wouldn't make sense not to use it. Just like any framework, you can go along fine without it, but sometimes using the right tool makes the job a lot easier.

As mentioned, it's worth checking out the "Mocks aren't stubs" article. Mocking frameworks allow mocking, stubbing and faking. In other words, they are very versatile.

unit testing - Why do we need mocking frameworks like Easymock , JMock...

unit-testing tdd mocking easymock stubs
Rectangle 27 9

You might want to read Martin Fowler's Mocks Aren't Stubs article. The basic difference is this:

  • A mock additionally expects calls to come in a specific order, with specific parameters, and will throw an exception when these expectations are not met.

There are some error condition that cannot be tested for with stubs. On the other hand, tests using mocks are often much less stable.

While stubs can be written manually with reasonable effort, Mocks would require far more work. And a good mocking framework can make writing stubs faster and easier as well.

Small point, Martin's article is getting a bit old now and misses some critical points. First, I don't think any of the current frameworks enforce invocation order unless you ask for it. Second, if your tests are unstable, that's useful feedback that should make you take another look at your design.

unit testing - Why do we need mocking frameworks like Easymock , JMock...

unit-testing tdd mocking easymock stubs
Rectangle 27 3

It's been a long time since I've used EasyMock, but isn't replay only supposed to be called once per mock in a test? You are calling it twice. Try getting rid of the first replay call.

In this case, does it make sense to have the field that contains the mock be public? In general, collaborators should be set via either constructor or setter, eliminating the need for reflection at all.

EDIT -- based on your updates -- the error indicates setDataType was called on the mock, but the mock did not expect it to be called. Perhaps your class is calling it twice, perhaps it is being called out of order, or calling it with an argument you didn't expect (although I would expect the error to be different in this case).

Corrected that and still having similar issue

r u sure the error is the same?

doing too many things same time, sorry. There is only one replay now. According to your question about public setter - there is no such possibility, because tested class cannot be changed.

java - How to inject EasyMock mock into tested class private field - S...

java reflection junit easymock
Rectangle 27 3

Here you can find a comparision between Mockito and EasyMock:

PowerMock is an extension of other Mocking frameworks like Mockito or EasyMock that comes with more powerful capabilities. It means that you can combine Mockito/EasyMock and PowerMock into the same unit test.

I personally use Mockito for unit testing big part of my code and PowerMock only in code that needs its extra features as testing static methods.

junit - What is the difference between PowerMock, EasyMock and Mockito...

junit mockito powermock easymock
Rectangle 27 2

This requires the EasyMock ClassExtension, which unfortunately can't mock private methods however.

warning: the methods used in the link are deprecated today, prefer the method described here tek6.blogspot.fr/2011/12/

java - EasyMock -- mock methods within tested class? - Stack Overflow

java junit easymock
Rectangle 27 2

The code is being run because it is inside a static initialization block. Once your test refers to EditorHelper, the JVM will load the class and this initialization block will run and attempt to create a SessionFactory from the AnnotationConfiguration instance which is configured with the config XML file.

Which class are you trying to test? I note that the test is EditorTest and the class is EditorHelper. Is this intentional, and are you actually trying to test an Editor class?

Aha, I see! I assumed the static block would run at import (because that's how Python does it). I'll try putting that initialization line in a try-catch.

You're pretty much right on about the test class. It's actually supposed to test several *Editor classes, which use some EditorHelper static methods to get database access. That's why I'm trying to mock a SessionFactory object rather than an EditorHelper.

If the EditorHelper is accessed statically, you won't be able to mock it and so there doesn't seem to be a good way to test the Editor classes. Can you inject the SessionFactory another way? Could you move the static initialization block into a static initialize method for use in production code and use setSessionFactory in testing?

I think what I'll probably do is put the SesssionFactory initialization into a really permissive try block so that it's free to fail, and then inject the mock SessionFactory object. I've gotten sidetracked away from this for a few days, but I'll update when I get back to it. I expect that to work, though.

Yes, that worked as expected. I will post the updated code. Thanks for pointing me in the right direction!

java - Mocking Hibernate's SessionFactory using EasyMock - Stack Overf...

java hibernate unit-testing junit easymock
Rectangle 27 1

I guess the test still needs to provide some value to the field annotated woth @Value, so it's easy to do it programmatically in your @Before method.

Yes. And if you want to add a mock in a Spring context, you can use EasyMock.mock as a factory.

java - EasyMock and @Value annotation - Stack Overflow

java spring junit easymock
Rectangle 27 1

When deleting something, I suggest returning the object you just deleted. It makes testing much, much easier and allows doing things after you deleted (e.g. showing notice, logging, etc). I think most (all?) Java collections are doing so.

About most / all. All Java collections inherit from the same interface, so if one returns the deleted object, all do.

This is all true and correct, however very slightly misses the intent of the test (as I understand it). Testing if PersonManager.delete() returns a Person instance is not the same as testing if it calls PersonDao.delete().

PersonPanager.delete()
boolean

Again true, but then you're testing if it returns true/false, not that the DAO is being called with the correct parameter.

java - Mocking void method with EasyMock and Mockito - Stack Overflow

java unit-testing mockito easymock
Rectangle 27 1

I think you have this mocking backwards. Mock myRepostory, then set up the myRepository mock to return a Criteria object and to return a project list when that Criteria object is passed to findList.

Task, Order and Project can probably just be instantiated.

Now, instance.getProjects(task) will return something. You can check to make sure that thing that got returned is the same thing you said should be returned from findList. Now you've actually tested something, albeit nothing particularly interesting.

You probably want to validate that the criteria object was set up correctly before it was passed to findList. To do that, you either have to make criteria a mock, then you can set up your expectations for what methods are called. The tricky part here is that Hibernate Restriction classes do not have a non-default equals implementation, so you have to write your own matcher to check that the Restrictions being passed to the criteria are the same (functionally) as the Restrictions you expect.

Another possibility is to set up criteria as an actual Criteria object. (You still set up your myRepository mock to return it.) Then, after the function is called, you can check the contents with some substring matching on the toString() method or any other ways you know to inspect the Criteria object.

A final (unit test) possibility is to not use a mocking framework for the Criteria object, but some hand-coded one that you write that allows you to inspect all of the Restrictions that were added to it.

All of this makes a good case for this method actually being tested with integration testing instead. You wind up doing a lot of work to verify some not very interesting things and your tests can become quite brittle if you try to refactor the code. (I've done it myself, so I speak from experience.)

Thanks a lot for your time. But the thing that I don't understand is that, if I mock the repository object and tell it to return these projects upon findList call. Then it would return what I have told it. So what should I compare it with when I have told it return what I want so it would return what I want whether the criteria works or not. The only thing is that I can initial projects and then just check if the criteria is correct or not. But can I also check whether it returns the correct thing with mocking repository as well?

the problem that I have with mocking here is that in general if I mock the repository and tell it what I expect as the return type then how can I test whether it returns the correct data? Am I missing something?

The point of the unit test (as opposed to integration testing) is that you don't want to test CreateMyRepositoryWrapper. You assume that that class is going to work correctly (based on other tests, you hope). In mocking, you say, "Suppose myRepository does this - does this method work as I expect?" In this way, you could easily test other scenarios, such as myRepository.findList returns null - do I want to return null or an empty list from this method? Suppose myRepository.findList throws an exception - do I want to handle that exception or just let it cascade?

java - Unit testing a method with easymock - Stack Overflow

java unit-testing junit easymock
Rectangle 27 2

Just like every other developer I find myself writing code instead of using the existing solution - the "not invented here" syndrome.

Your question suggest that you prefer to write the classes you need to fake/mock twice instead of use a framework that would do that for you. Using a mocking framework frees you from needing to write, refactor and update your hand rolled mocks whenever you change the faked object.

In other words using a mocking framework is just like any other 3rd party library e.g. ORM - someone else wrote the code so you don't have to.

unit testing - Why do we need mocking frameworks like Easymock , JMock...

unit-testing tdd mocking easymock stubs
Rectangle 27 2

I started the same way (writing mocks by hand) and by now I have almost completely switched over to EasyMock.

Typically the very first time I need a mock, I can have it in a couple of lines of code with EasyMock, whereas by hand I need to implement the needed interface (fair enough, this can be generated by an IDE like IntelliJ) and then add the necessary code to produce the needed response and/or to allow sensing the effects of calls to it.

Fine, one might say, that's a one-time cost only. The next time I can just reuse the hand written mock happily... I found that's often not the case. In another test I might need a mock of the same class with different behaviour. E.g. different methods are called, and/or different result is expected. A specific case is when the mock is expected to throw an exception in one test case, but not in another. Fine, I can add some parameters to it which control the behaviour dynamically. Then for the next test, some more parameters to control more behaviour... so I end up with an ever more complicated mock implementation, which is a dependency for ever more unit tests - posing also a risk of inadvertently breaking older tests.

As opposed to this, with EasyMock I can configure my mocks independently for each test. Thus the behaviour is explicitly controlled and visible within the unit test code itself, and there is no risk of side effects.

Not to mention that with EasyMock you can verify that the required methods are called in the required order, if you need to (and I do, every now and then). Implementing this by hand (especially in a generic fashion) would be quite pain in the neck, for no added benefit.

unit testing - Why do we need mocking frameworks like Easymock , JMock...

unit-testing tdd mocking easymock stubs
Rectangle 27 1

If you control your design and you should be mostly ok with Mockito. For example PowerMock allows you to mock a private member which looks cool, but is not necessary if you refactor that private member to a parameter provided through dependency injection.

junit - What is the difference between PowerMock, EasyMock and Mockito...

junit mockito powermock easymock