Java – how to start testing (jmock)
I'm trying to learn how to write tests I'm also learning Java. Someone told me that I should learn / use / practice jmock. I found some articles on the Internet that are helpful for some extensions:
http://www.theserverside.com/news/1365050/Using-JMock-in-Test-Driven-Development
http://jeantessier.com/SoftwareEngineering/Mocking.html#jMock
Most of the articles I found were about test - driven development, writing tests first and then writing code to pass the tests I'm not looking now, I'm trying to write tests for existing code using jmock
Official documentation is at least vague to me. It's too difficult for me Does anyone have a better way to learn this Good books / links / tutorials are very helpful to me thank you
Edit – more specific questions:
http://jeantessier.com/SoftwareEngineering/Mocking.html#jMock – from this article
Try this to simulate this simple class:
import java.util.Map; public class Cache { private Map<Integer,String> underlyingStorage; public Cache(Map<Integer,String> underlyingStorage) { this.underlyingStorage = underlyingStorage; } public String get(int key) { return underlyingStorage.get(key); } public void add(int key,String value) { underlyingStorage.put(key,value); } public void remove(int key) { underlyingStorage.remove(key); } public int size() { return underlyingStorage.size(); } public void clear() { underlyingStorage.clear(); } }
Here's how I try to create a test / simulation:
public class CacheTest extends TestCase { private Mockery context; private Map mockMap; private Cache cache; @Override @Before public void setUp() { context = new Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; mockMap = context.mock(Map.class); cache = new Cache(mockMap); } public void testCache() { context.checking(new Expectations() {{ atLeast(1).of(mockMap).size(); will(returnValue(int.class)); }}); } }
It passed the test and basically did nothing. What I want is to create a map and check its size. You know, work some changes and try to catch this It's better to understand through examples. Other contents or any other exercises I test here are very helpful to me TNX
Solution
This is a tutorial about using JUnit and easymock (a simulation library that I personally think is easier to use than jmock): http://www.michaelminella.com/testing/unit-testing-with-junit-and-easymock.html
Even if you are 100% committed to using jmock, the concepts between the two are the same, which can help you better understand them
The purpose of simulation is that when you test class a that depends on B and C, you use the simulated versions of B and C to specify their exact behavior instead of using your real implementation of B and C Test of A Otherwise, instead of testing only a single unit of a, you also implicitly test B and C