1

which guru know's the best practice to test the behavier of this class, so that whenever AsyncCallback is called, it should go into onSuccess method. To print out "onSuccess".

@RunWith(MockitoJUnitRunner.class)
public class InterfaceTest {

    @Mock
    private Service service;

    private Employee employee;

    @Before
    public void setUp() throws Exception {
        employee = mock(Employee.class);
    }

    @Test
    public void testMockBehavier() throws Exception {

    }
}

interface AsyncCallback {
    void onError();
    void onSuccess();
}

class Employee {

    @Autowired
    Service service;

    public void save(){
        service.save(new AsyncCallback() {
            @Override
            public void onError() {
                System.out.println("Error");
            }

            @Override
            public void onSuccess() {
                System.out.println("Success");
            }
        });
     }
}

interface Service {
    void save(AsyncCallback asyncCallback);
}

I haven't found out how to access an anonymous inner class. Very appreciate for good practice tipps.

Thanks

  • Marking this as a dupe of [Calling callbacks with Mockito](http://stackoverflow.com/q/13616547/1426891); the fact that it's an anonymous inner class rather than a named class is entirely an implementation detail. Please let me know if there is anything about the answers there that are inapplicable to your question, and I can reopen the question here. – Jeff Bowman Jun 14 '16 at 01:18

1 Answers1

2

If I understand correctly, the class under test is Employee. So if there is one class that you should NOT mock, it's Employee.

Second, you need to inject the mock service into the employee under test.

Third, you need to tell the mock service to call the success callback when save() is called.

@RunWith(MockitoJUnitRunner.class)
public class InterfaceTest {

    @Mock
    private Service service;

    @InjectMocks
    private Employee employee;

    @Test
    public void testSuccess() throws Exception {
        Answer<Void> answer = new Answer<Void>() {
            Void answer(InvocationOnMock invocation) {
                AsyncCallback callback = invocation.getArguments()[0];
                callback.onSuccess();
                return null;
            }
        };
        doAnswer(answer).when(service).save(any(AsyncCallback.class));

        employee.save()

        // TODO: now check that the success callback does what it's supposed to do
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255