0

I have a controller

@Controller
public class SomeController extends BaseController {

    @RequestMapping(method=POST, value="/something")
    public @ResponseBody SomeReturnType createReturnType(@Requestbody SomeReqBody someReqBody, Object obj) {
        return someMethod(someReqBody,"SomeString");
    }

    public SomeReturnType someMethod(SomeReqBody someReqBody, String someString) {
        return someProtectedMethodFromBaseController(someReqBody, someString);
    }
}

I need to test the method createReturnType() using JUnit and Mockito. So I wrote some piece of code in test class as follows :

 @RunWith(MockitoJunitRunner.class)
public class testSomeController {

    @Mock
    SomeController someControllerMock = new SomeController();

    @Test
    public void test createReturnType() {
        SomeReqBody someReqBody = mockRequestBody();
        SomeReturnType someReturnType = mockRetruntype();
        Object someObject = mockObject();
        when(someControllerMock.someMethod(someReqBody,"SomeString")).thenReturn(someReturnType);
        SomeReturnType returnTypeExp = someControllerMock.createReturnType(someReqBody, someObject);
        assertNotNull(returnTypeExp);
    }
}

Now the problem is that everything works fine in the test except the expected result is always null. I couldn't find where I did things wrong. Can someone figure out the problem?

Anzz
  • 11
  • 4
  • The class under test should not (usually) be mocked, otherwise the test is just testing mockito and not the class to be tested. Also, `someString` != `SomeString`. – Andrew S Aug 05 '22 at 18:36
  • @AndrewS I tried using '@InjectMocks 'and nothing happened. Also "someString" was a typo. – Anzz Aug 08 '22 at 07:39
  • You're CUT (class under test) is a mock so you can't actually interact with it. You need to create a real instance or use `@InjectMock` for it. If you want to mock internal public methods of that class so mix up mock and real object then you should use a spy-object which is expansive so avoid it if possible. – LenglBoy Aug 08 '22 at 08:18
  • Now I tried using @InjectMocks, but now even if the `when` is specified,the `someProtectedMethodFromBaseController(someReqBody)` is always called. Don't know why.any idea? – Anzz Aug 08 '22 at 10:53
  • If you want to actually call one method and mock another, you should use partial mocking. See the question and answer here: https://stackoverflow.com/questions/73275655/how-to-mock-return-value-without-mocking-object – Jonasz Aug 09 '22 at 05:31

0 Answers0