I have created a service class
@Service
public class SomeServiceImpl implements SomeService {
@Override
public ResponseEntity<?> getMethod() {
EntityClass entity = new EntityClass();
//Some operations to manipulate entity
return new ResponseEntity<>("entity", HttpStatus.OK);
}
}
I'm trying to get the object in a test class using Mockito:
@AutoConfigureMockMvc
@RunWith(MockitoJUnitRunner.class)
@Slf4j
public class SomeServiceTest {
@Mock
SomeService someService;
@Test
public void getMethodSomeService(){
ResponseEntity<?> responseEntity=someService.getMethod();
log.debug("{}", responseEntity);
}
}
However, responseEntity
is always null
. What am I doing wrong? Am I missing something? Why the value I got is always null?
By writing
@Mock
SomeService someService;
You have created a mock, all method calls to that mock will return null unless you tell it to do otherwise with something like this
when(someService.someMethod(any())).thenReturn("something");
Because of this someService.getMethod()
will always return null. You are probably looking to not use a mock in this case, mocks are usually used to prevent calls to other objects that aren't supposed to be part of the unit test.
Mocking means replacing a concrete implementation with something you can manipulate from the outside. If you want to test your SomeServiceImpl
, you can just create a new instance.
SomeService service = new SomeServiceImpl();
This instance can then be tested.
If your SomeService
had a dependency to let's say another Service, you might need to mock this dependency in order to control its behaviour.
@Mock
OtherService dependency;
SomeService someService = new SomeServiceImpl(dependency);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.