Search code examples
javajuniteasymock

Testing my UserService class, but need to mock a method that gets called at the same time


I am testing my userService classes method, but the method I am testing makes a call to another method.

@Test
public void testSomething() {
  HelloWorldResponse hwResponse = ....;

  expect(userDaoMock.helloWorldCall(....).andReturn(hwResponse);

  reploy();

  UserResponseCode response = userService.register(user);

  assertEquals(UserResponseCode.OK, response);
}

Now say my register method makes a call to another method in my userService class, how can I mock that call?

From what I understand I can't do that since I am not wrapping the entire userService class in a mock right?

Update

When I debug my register methods' junit test, I see this:

SomeThing thing = helloWorldCall(...);  // userService.helloWorldCall(...);

Now the method helloWorldCall just returns what a userDao returns, and I have already mocked that in my test, but for some reason it is returning null when I trace execution, so thing == null.

Why is it null, shouldn't it have the value that is returned by my mock?

The UserService#helloWorldCall code is below, again it simply returns what the userDao returns which again I have mocked as you can see above which returns that response I hard coded in my unit test. Why is it null when I trace/debug the unit test?

public HelloWordResponse helloWorldCall(...) {
  return userDao.helloWorldCall(..)
}

Solution

  • I am using a mockscontrol

    private IMocksControl mockMaker;
    

    So I have to use

    mockMaker.replay();
    mockMaker.verify();
    

    It works now since I had many different mock objects.