Java – Is mocking for unit testing appropriate in this scenario

javamockingunit testing

I have written around 20 methods in Java and all of them call some web services.
None of these web services are available yet. To carry on with the server side coding, I hard-coded the results that the web-service is expected to give.

Can we unit test these methods? As far as I know, unit testing is mocking the input values and see how the program responds. Are mocking both input and ouput values meaningful?

Edit :

The answers here suggest I should be writing unit test cases.

Now, how can I write it without modifying the existing code ?

Consider the following sample code (hypothetical code) :

    public int getAge()
    {
            Service s = locate("ageservice"); // line 1
            int age = s.execute(empId); // line 2
             return age; // line 3

 }

Now How do we mock the output ?

Right now , I am commenting out 'line 1' and replacing line 2 with int age= 50. Is this right ? Can anyone point me to the right way of doing it ?

Best Answer

Yes.

Use mocks and stubs to simulate the web services' expected behavior. Validate that your code functions correctly under all expected boundary values and equivalence classes.

EDIT:

No, you should not be manually editing the unit test with int age= 50. You should be using dependency injection so that you can easily replace the Service with a mock object.

public int getAge(Service s)
{
    int age = s.execute(empId); // line 2
    return age; // line 3
}

Your unit test should look something like the following pseudo-code:

public int getAgeMinimumValueTest()
{
    ClassUnderTest uut = new ClassUnderTest();
    MockService service = new MockService();
    service.age = 10;
    int age = uut.getAge(service);
    Assert(age == 10);
}
Related Topic