Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. Mocking Random With JMockit
  2. ===========================
  3.  
  4. If you had already tried cover same bigger part of code with JUnit tests, you had probably already meet with it.
  5. With JUnit we can run tested code with predefined input and check output of it.
  6. But what if this code use on background without control of calling code same objects, which give non-deterministic output, like random numbers generator?
  7. Or system time? How can we cover such code with tests?
  8.  
  9. This situation can be solved by mocking such non-deterministic parts out.
  10. Mocking is creating fake objects, which will act role of object which we want get out of the test.
  11. This fake objects will be spoofed on place of them and tested code will use within our test fake object instead of unpleasant real objects.
  12.  
  13. In this tutorial we will show example, how to mock objects of classes of JDK.
  14.  
  15.  
  16.  
  17. <dependency>
  18. <groupId>org.jmockit</groupId>
  19. <artifactId>jmockit</artifactId>
  20. <version>${version.jmockit}</version>
  21. <scope>test</scope>
  22. </dependency>
  23.  
  24.  
  25. public static class SystemMock extends MockUp<System> {
  26. @Mock
  27. public long currentTimeMillis(){
  28. return 123;
  29. }
  30. @Mock
  31. public long nanoTime(){
  32. return 1234;
  33. }
  34. }
  35.  
  36. public static class RandomMock extends MockUp<Random> {
  37. @Mock
  38. public void $init(Invocation inv) throws Exception {
  39. Field field = Random.class.getDeclaredField("seed");
  40. field.setAccessible(true);
  41. field.set(inv.getInvokedInstance(), new AtomicLong(7326906125774241L));
  42. }
  43. }
  44.  
  45. public static class SecureRandomMock extends MockUp<SecureRandom> {
  46. Random random = new Random();
  47. @Mock
  48. public void nextBytes(byte[] bytes){
  49. random.nextBytes(bytes);
  50. }
  51. }
  52.  
  53. @BeforeClass
  54. public static void installMockClasses() throws Exception {
  55. new SystemMock();
  56. new RandomMock();
  57. new SecureRandomMock();
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement