0

I try testing my LocalServiceUtil classes, generated by service builder, with PowerMock but always getting 'null' or '0' from Util's methods.

Test class

@RunWith(PowerMockRunner.class)
@PrepareForTest(EntityLocalServiceUtil.class)
public class EntityTest {

        @Test
        public void testGetAnswer() throws PortalException, SystemException {
                PowerMockito.mockStatic(EntityLocalServiceUtil.class);
                assertEquals("hello", EntityLocalServiceUtil.getHello());
        }
}

Util class contains

public static java.lang.String getHello() {
            return getService().getHello();
}

and this service working correctly on deployed portlet. What i do wrong?

dmitrievanthony
  • 1,501
  • 1
  • 15
  • 41

1 Answers1

1

You have forgot to mock the methode:

    @Test
    public void testGetAnswer() throws PortalException, SystemException {
            PowerMockito.mockStatic(EntityLocalServiceUtil.class);
            when(EntityLocalServiceUtil.getHello()).thenReturn("hello"); // <- here
            assertEquals("hello", EntityLocalServiceUtil.getHello());
    }
Mark
  • 17,887
  • 13
  • 66
  • 93
  • 1
    Ok, but where we testing out method? In this case EntityLocalServiceUtil.getHello() will always return "hello", but method from Util and Impl classes will not be called, correct? – dmitrievanthony Aug 16 '12 at 14:24
  • Yes. The target of unit testing is to test only your unit code, independent of other classes. Therefore you need to encapsulate this code from other infrastructure, like Services of Liferay. That you can do with mock approach. – Mark Aug 16 '12 at 14:50
  • See the approach with PowerMock here http://stackoverflow.com/questions/9701539/testing-for-custom-plugin-portlet-beanlocatorexception-and-transaction-roll-bac/11856097#11856097 . There we have a independent method for calculate the age, but this method get the User from UserLocalServiceUtil, therefore for the Test we encapsulate the logic of UserLocalServiceUtil and test only our method for age calculation. – Mark Aug 16 '12 at 14:55
  • But how to directly use Util classes with out implementation methods/fields of something special for test classes? I find only one solution - deploy test-portlet on server and run with JUnitCore.runClasses(...) Is there some like this solution, but for execution with ant? – dmitrievanthony Aug 16 '12 at 15:51
  • 1
    If you need unit-test, then you don't to deploy something to the server. The unit-test tests mostly small programm logic, without server and other infrastructure. May be you need integration-test? – Mark Aug 16 '12 at 22:06
  • Yes, now i think so too. Thanks. – dmitrievanthony Aug 17 '12 at 07:24