I have this (simplified) service class:
public interface EventListener {
void call();
}
public class MyService {
private final EventListener eventListener;
private final List<String> elements = new LinkedList<>();
public MyService(EventListener eventListener) {
this.eventListener = eventListener;
}
public void addElement(String element) {
elements.add(element);
eventListener.call();
}
public void removeElement(String element) {
elements.remove(element);
eventListener.call();
}
}
And this test method:
#Test
public void remove_should_call_event_listener() {
// arrange
EventListener eventListener = Mockito.mock(EventListener.class);
MyService myService = new MyService(eventListener);
myService.addElement("dummy");
// act
myService.removeElement("dummy");
// assert
Mockito.verify(eventListener).call();
}
How can I tell Mockito to ignore calls of eventListener.call() during "arrange" and verify only calls during "act"? I want to verify that eventListener.call() was called during myService.removeElement(...) and ignore all other calls.
Just before acting, call:
Mockito.reset(eventListener); // resets the set-up also
or
Mockito.clearInvocations(eventListener) // resets only the invocation history
Related
I'm fairly new to Mockito, and I've been looking for a way to verify that if I call the filter() method with the right string, that the foo method will get called once.
public class A
{
private final Config _config;
public A(Config config) { _config = config; }
public void filter(String str)
{
if(str.startsWith("a"))
{
if(str.contains("z"))
{
foo(config.getName());
}
}
}
private void foo(String bar)
{
(...)
}
}
Here is my current code:
#Test
public void testOne()
{
Config config = new Config(configFile);
A a = Mockito.spy(new A(config));
a.filter("abcz");
verify(a, times(1)).foo(someString);
}
Try to be more generic while such a test. If you don't need to specify what exactly argument should by passed then just use any():
import static org.mockito.ArgumentMatchers.any;
verify(a).foo(any(String.class));
I have a Processor class which implements Runnable.
The first method
Public Processor implements Runnable{
//"Event" is the name of this queue
PersistentQueue<Event> persistentQueue = new PersistentQueue<>("Event");
//add the Event POJO to the persistentQueue
public void addToQueue(Event, event) {
persistentQueue.add(event);
}
The persistentQueue is to store Event POJO
And the run method
public void run() {
while (true) {
if (!persistentQueue.isEmpty()) {
Event peekEvent = persistantQueue.peek();
sendRequest(peekEvent);
}
}
}
public void sendRequest(Event, event){
// do something to send the event
}
For the first addToQueue method I wrote the test
public class ProcessorTest {
private Event event;
private Processor m_Processor;
#Before
public void setup() throws IOException {
//the Processor class is a singleton
m_Processor = Processor.getProcessor();
event = new Event();
}
#Test
public void test(){
PersistentQueue<Event> persistentQueue = new PersistentQueue<>
("Event");
m_Processor.addToQueue(event);
assertEquals(1, persistentQueue.size());
}
}
But the queue size is 0 not 1. I dont know what's the problem. And I also have question about how to test the run method?
In your test method, you created a new queue that has nothing to do with your m_Processor instance; it goes unused entirely. You need to change your code so you can get the PersistentQueue instance contained inside your m_Processor instance. Assuming you have a getter method called getPersistentQueue inside Processor, then you can use the following:
#Test
public void test() {
m_Processor.addToQueue(event);
assertEquals(1, m_Processor.getPersistentQueue().size());
}
I want to create a test for presenter class using mockito tried few ways but getting error mention below. I am following these links here and here and my presenter class
public class SignInPresenterImpl extends BasePresenterImpl implements SignInPresenter {
private SignInView mSignInView;
private SignInInteractor mSignInInteractor;
/**
* Constructor
*
* #param signInView the associated SignIn view
*/
public SignInPresenterImpl(#NonNull final SignInView signInView) {
mSignInView = signInView;
mSignInInteractor = new SignInInteractorImpl();
}
#Override
public void onSignInClicked(final String email, final String password) {
// checking for validation
if (!ValidationUtil.checkEmail(email)) {
mSignInView.showErrorMessage(R.string.error_invalid_email);
return;
}
if (!ValidationUtil.checkPassword(password)) {
mSignInView.showErrorMessage(R.string.error_invalid_password);
return;
}
mSignInView.showLoading();
mSignInInteractor.login(email, password, new BaseInteractor.ApiListener() {
#Override
public void onSuccess(final CommonResponse commonResponse) {
//todo handle success
}
#Override
public void onFailure(final ApiError apiError, final Throwable throwable) {
if (isViewAttached()) {
mSignInView.hideLoading();
if (apiError != null) {
mSignInView.showErrorMessage(apiError.getMessage());
} else {
// resolve error through throwable
mSignInView.showErrorMessage(parseThrowableMessage(throwable));
}
}
}
});
}
}
and my presenter test class is
public class SignInPresenterImplTest {
#Mock
BaseInteractor.ApiListener listener;
#Mock
private SignInView mSignInView;
#Mock
private SignInInteractor mSignInInteractor;
private SignInPresenter signInPresenter;
#Before
public void setUp() throws Exception {
// Mockito has a very convenient way to inject mocks by using the #Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this);
//Get a refrence to the class test.
signInPresenter = new SignInPresenterImpl(mSignInView);
}
#Test
public void signInAndShowProgress() {
signInPresenter.onSignInClicked("", "");
mSignInView.showErrorMessage("");
verify(mSignInView).showLoading("Loading");
}
}
mSignInView shows below error
Wanted but not invoked: mSignInView.showLoading("Loading");
Please suggest me how to implement test cases in a correct way what I am doing wrong in it.
Thanks in advance
In your method under test, the showLoading method is invoked with no attributes.. i think you should expect that and possibly verify that no error message has been shown:
#Test
public void signInAndShowProgress() {
signInPresenter.onSignInClicked("", "");
verify(mSignInView, times(0)).showErrorMessage(Mockito.any(String.class));
verify(mSignInView).showLoading();
}
for a unit tests i am trying to verify if there is
a way to verify a method call inside a method with mockito verify?
An example would be:
public delete(param) {
VideoService.deleteVideo(param); << i want to verify the call of this method
return etc..
}
I can check if delete is called with :
verify(mock,times(1)).delete(param);
Is there also like a way to check the inside method like:
verify(mock,times(1)).delete(param).VideoService.deleteVideo(param);
You can use a spy.
public class MyVideoService {
private VideoService videoService;
public MyVideoService(VideoService videoService) {
this.videoService = videoService;
}
public void delete(String param) {
videoService.deleteVideo(param);
}
}
public class VideoService {
public void deleteVideo(String param) {
}
}
If you now want to test an object that uses MyVideoService. E.g.
public class ObjectThatUsesMyVideoService {
private MyVideoService myVideoService;
ObjectThatUsesMyVideoService(MyVideoService myVideoService) {
this.myVideoService = myVideoService;
}
public void deleteVideo(String param) {
myVideoService.delete(param);
}
}
You can write a test like this
public class MyVideoServiceTest {
#Test
public void delete(){
// VideoService is just a mock
VideoService videoServiceMock = Mockito.mock(VideoService.class);
// Creating the real MyVideoService
MyVideoService myVideoService = new MyVideoService(videoServiceMock);
// Creating a spy proxy
MyVideoService myVideoServiceSpy = Mockito.spy(myVideoService);
ObjectThatUsesMyVideoService underTest = new ObjectThatUsesMyVideoService(myVideoServiceSpy);
underTest .deleteVideo("SomeValue");
// Verify that myVideoService was invoked
Mockito.verify(myVideoServiceSpy, Mockito.times(1)).delete("SomeValue");
// Verify that myVideoService invoked the VideoService
Mockito.verify(videoServiceMock, Mockito.times(1)).deleteVideo("SomeValue");
}
}
Lets assume you have a class
class MyVideoService {
final VideoService videoService;
public MyVideoService(VideoService videoService) {
this.videoService = videoService;
}
public void delete(param) {
videoService.deleteVideo(param);
}
}
Then you mock VideoService with
VideoService videoService = mock(VideoService.class);
And create MyVideoService with this mocked instance, call method, verify:
MyVideService myVideoService = new MyVideoService(videoService);
myVideoService.delete (param);
verify(videoService, times(1)).deleteVideo(param);
I want to create a mock in my setUp method, but define the concrete return values in each test method.. is this somehow possible?
Ex:
private List<Long> list;
#Before
public void setUp() {
when(mock.xxx()).thenReturn(list);
}
#Test
public void testEmptyList() {
list = new ArrayList<Long>();
// method call
}
#Test
public void testWithOneElement() {
list = Arrays.asList(Long.valueOf(125L));
// method call
}
Edit:
Best case i could have is this:
private List<Long> list = new ArrayList<Long>();
#Before
public void setUp() {
when(mock.xxx()).thenReturn(list);
}
#Test
public void testEmptyList() {
// method call
}
#Test
public void testWithOneElement() {
list.add(Long.valueOf(123L));
// method call
}
Since Java passes value by Reference, as long as we do not assign a new list to the list, we can add values, and mock will work with the updated list.
But is this kind of behaviour somehow possible even with the changed ObjectIds? So i mock a method call, but define what to return later?
Ex:
private List<Long> list;
#Before
public void setUp() {
when(mock.xxx()).thenReturn(list);
}
#Test
public void testEmptyArrayList() {
list = new ArrayList<Long>();
// method call
}
#Test
public void testEmptyLinkedList() {
list = new LinkedList<Long>();
// method call
}
You can add when(mock.xxx()).thenReturn(list); to both your testcase separately and not in setUp(). then return emplty list in testEmpty and return list with one element in testWithOneElement
private List<Long> list;
#Before
public void setUp() {
// Other setup here
}
#Test
public void testEmptyList() {
list = new ArrayList<Long>();
when(mock.xxx()).thenReturn(list); // return list with no element
// method call
}
#Test
public void testWithOneElement() {
list = Arrays.asList(Long.valueOf(125L));
when(mock.xxx()).thenReturn(list); // return list with one elemet
// method call
}
So.. after some trial and error, I have made sth like this:
private List<Long> list;
#Before
public void setUp() {
when(mock.xxx()).thenAnswer(
new Answer<List<Long>>() {
#Override
public List<Long> answer(final InvocationOnMock invocation) {
return list;
}
});
}
#Test
public void testEmptyArrayList() {
list = new ArrayList<Long>();
// method call
}
#Test
public void testEmptyLinkedList() {
list = new LinkedList<Long>();
// method call
}
Since we now define in setUp, not "return value", but "the called method which prepares the return value", and since this method will be called at runtime first, we do not get a nullPointer, and the values we assign in each method will be returned.