I doubt whether it can be achieved with unitils. But please consider using PowerMock instead which seems to be capable of handling what you need. It can mock static methods,private methods and more (Ref: PowerMock)
How to mock static methods using UnitilsJUnit4?
-
12-12-2021 - |
Frage
I have method getAllCustomers
inside CustomerService
class. Inside this method I call another static method from CustomerDao
class.
Now when I am writing the junit for method getAllCustomers
inside customerService
class, where I want to mock the call to
static method of CustomerDao
i.e. getAllCustomers
. Here is the brief code snippet of method getAllCustomers
inside
CustomerService
class. Is it possible to mock the static method call using unitils?
Public static List<CustomerDate> getAllCustomers()
{
//some operations
List<CustomerDate> customers=CustomerDao.getAllCustomers();// static method inside CustomerDao
//some operations
}
Above code is just an example I am trying to put. Please avoid the discussion why these methods are designed as static methods. That's a separate story .)
Lösung
Andere Tipps
This would be a matter of:
- Setting up the mock
- Calling the mock and expecting some data back
- Verifying the end result of your call given your data
So, without really much ado about the static call, here's the way you can set it up in PowerMock:
@RunWith(PowerMockRunner.class)
@PrepareForTest(CustomerDao.class)
public class CustomerTest {
@Test
public void testCustomerDao() {
PowerMock.mockStatic(CustomerDao.class);
List<CustomerDate> expected = new ArrayList<CustomerDate>();
// place a given data value into your list to be asserted on later
expect(CustomerDao.getAllCustomers()).andReturn(expected);
replay(CustomerDao.class);
// call your method from here
verify(CustomerDao.class);
// assert expected results here
}
}