Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a mock object filled with arbitrary values

I'm new to java and have to test classes.

I need a mock object for a very complicated class, where some properties are objects, which in turn have other objects so forth, so for me to manually generate a mock object is a lot of work to do.

I was wondering if there is a way to generate that mock object automatically, but not just that, also if is possible to automatically fill all the properties of that object with some arbitrary values.

Could somebody help me on this, please?

I'm going to put an example here, to be sure I made myself clear...

class A {
int a;
B b;
C c;
}

class B {
int x;
C k;
}

class C {
String x;
int x;
}

And I want to mock an object of the A class.

I want that mockA object to have values for all possible fields, for example for the x String from the B class also...

like image 741
niceman Avatar asked Aug 30 '13 12:08

niceman


1 Answers

Mockito and RETURNS_DEEP_STUBS option might be what you're looking for. What's more, mockito seems often to return sensible values by default.

Example usage from the linked documentation, for quick reference:

Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);

// note that we're stubbing a chain of methods here: getBar().getName()
when(mock.getBar().getName()).thenReturn("deep");

// note that we're chaining method calls: getBar().getName()
assertEquals("deep", mock.getBar().getName());
like image 172
Marcin Łoś Avatar answered Sep 19 '22 15:09

Marcin Łoś