Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If it is absolutely crucial that the return type is <code>long</code>, and you want to make sure that future changes don't inadvertently change this, then you don't need easymock. Just do this:</p> <pre><code>@Test public void TestGenerateIDReturnsLong() { Method method = VGenerator.class.getDeclaredMethod("generateID", new Class[0]); Assert.Equals(long.Class, method.GetReturnType()); } </code></pre> <p>Currently you are generating a mock implementation of <code>VGenerator</code>, and then you test the mock. This is <strong>not</strong> useful. The point of unit testing is to test a real implementation. So now you might be wondering what mocks are good for?</p> <p>As an example, imagine that <code>VGenerator</code> needs to use a random number generator internally, and you provide this in the constructor (which is called "dependency injection"):</p> <pre><code>public VGenerator { private final RandomNumberGenerator rng; // constructor public VGenerator(RandomNumberGenerator rng) { this.rng = rng; } public long generateID(length) { double randomNumber = this.rng.getRandomNumber(); // ... use random number in calculation somehow ... return id; } } </code></pre> <p>When implementing <code>VGenerator</code>, you are not really interested in testing the random number generator. What you are interested in is how <code>VGenerator</code> calls the random number generator, and how it uses the results to produce output. What you want is to take full control of the random number generator for the purpose of testing, so you create a mock of it :</p> <pre><code>@Test public void TestGenerateId() { RandomNumberGenerator mockRNG = createMock(RandomNumberGenerator.class); expect(mockRNG.getRandomNumber()).andReturn(0.123); replay(mockRNG); VGenerator vgenerator = new VGenerator(mockRNG); long id = vgenerator.generateID(); Assert.Equals(5,id); // e.g. given random number .123, result should be 5 verify(mockRNG); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload