-1

i am doing unit tests for my program, but i got a problem. i don't know how to deal with the situation that function A calls function and i am just going to test function A. it is said that i am supposed to create a stub module to simulate function as stub module. but i just don't know how to do this by JUnit. for example:

public class compute
{
    public int multiply(int a,int b)
    {
        return a*b;
    }
    public int cube(int a)
    {
        return(multiply(multiply(a,a),a);
    }
}

So, in this case, how to write test code for function cube()? how to simulate multiply()?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
HigginsWang
  • 13
  • 1
  • 2
  • I'd argue that there is no need to stub or mock anything in this case. – Hulk Sep 10 '16 at 09:41
  • thank you for your advice, but could you please me in what condition that stubs or mocks are needed and why they are not in need in this case? if i don't use stub so how can i find out the bug if function multiply() does contains error? – HigginsWang Sep 10 '16 at 09:47
  • If multiply function has a bug you will get to know it in the test case written for multiply method. – Madhusudana Reddy Sunnapu Sep 10 '16 at 09:51

3 Answers3

0

You don't need to create a stub/mock here to simulate multiply method.

You usually use them when you are calling a method on a different object. For ex, from a service class you are calling a dao class, then you stub/mock the dao class. Said that, as Alan indicated you can always have a partial mock/anonymous class/override to stub/mock only certain functions of a class under test.

Here in your case you just need to test cube method as it is and no need to mock multiply.

0

Probably no reason to mock anything here and indeed with your cube() method as it is it is problematic. However you can test the methods of a class in isolation if required by either using a mocking framework such as Mockito to create a partial mock (i.e. mock some methods of a class but call the real code for others) or simply override the multiply() method in an anonymous class such as below although you would need to change your code in cube to a * multiply(a, a)

@Test
public void testCube(){
    compute c  = createMock(9);
    Assert.assertTrue(27, c.cube(3));
}

public compute createMock(final int result){
    compute c = new compute(){
        @Override
        public int multiply(int a, int b){
            return result;
        }
    };
}
Alan Hay
  • 22,665
  • 4
  • 56
  • 110
0

If you were desperate to mock this method, this can be done by subclassing this class and providing a mock implementation of the relevant method(s) there.

That said, in this case it's really not necessary as you are not really relying on any third-party objects. If you later decide to change your implementation of cube to not use the multiply method, you'd have to rewrite your tests.

Joe C
  • 15,324
  • 8
  • 38
  • 50