Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Mocking Random With JMockit
- ===========================
- If you had already tried cover same bigger part of code with JUnit tests, you had probably already meet with it.
- With JUnit we can run tested code with predefined input and check output of it.
- But what if this code use on background without control of calling code same objects, which give non-deterministic output, like random numbers generator?
- Or system time? How can we cover such code with tests?
- This situation can be solved by mocking such non-deterministic parts out.
- Mocking is creating fake objects, which will act role of object which we want get out of the test.
- 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.
- In this tutorial we will show example, how to mock objects of classes of JDK.
- <dependency>
- <groupId>org.jmockit</groupId>
- <artifactId>jmockit</artifactId>
- <version>${version.jmockit}</version>
- <scope>test</scope>
- </dependency>
- public static class SystemMock extends MockUp<System> {
- @Mock
- public long currentTimeMillis(){
- return 123;
- }
- @Mock
- public long nanoTime(){
- return 1234;
- }
- }
- public static class RandomMock extends MockUp<Random> {
- @Mock
- public void $init(Invocation inv) throws Exception {
- Field field = Random.class.getDeclaredField("seed");
- field.setAccessible(true);
- field.set(inv.getInvokedInstance(), new AtomicLong(7326906125774241L));
- }
- }
- public static class SecureRandomMock extends MockUp<SecureRandom> {
- Random random = new Random();
- @Mock
- public void nextBytes(byte[] bytes){
- random.nextBytes(bytes);
- }
- }
- @BeforeClass
- public static void installMockClasses() throws Exception {
- new SystemMock();
- new RandomMock();
- new SecureRandomMock();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement