In unit custom runner I want to perform action before and after running the test action,
so I came around with this solution.
how solid is doing it that way, is there a more clean way to achieve that?
public class SomeCustomRunner extends BlockJUnit4ClassRunner {
private int m_testMethodIndex = 0;
private int m_testMethodsCount = 0;
private boolean m_sessionSetup = false;
#Override
protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
if(m_sessionSetup == false) {
m_sessionSetup = true;
beforeTestClass(); //->> DO MY STUFF HERE
}
super.runChild(method, notifier);
m_testMethodIndex++;
if(m_testMethodIndex == m_testMethodsCount) {
afterTestClass(); //->> DO MY STUFF HERE
}
}
#Override
protected List<FrameworkMethod> getChildren() {
List<FrameworkMethod> methods = super.getChildren();
m_testMethodsCount = methods.size();
return methods;
}
}
Instead of creating a separate test runner, you can define the actions to perform before and after in the test class itself in methods annotated with #BeforeClass resp. #AfterClass.
To reuse them in more than one test you can easily inherit them from a base class.
the easiest way is override the run method as below:
public class LifecycleRunner extends BlockJUnit4ClassRunner {
public LifecycleRunner(Class<?> klass) throws InitializationError {
super(klass);
}
#Override
public void run(RunNotifier notifier) {
beforeRunTests();
try {
super.run(notifier);
} finally {
afterRunTests();
}
}
private void afterRunTests() {
trace();
}
private void beforeRunTests() {
trace();
}
private void trace() {
System.out.println(Thread.currentThread().getStackTrace()[2]);
}
}
To gain full control over test execution, install a proper RunListener in your runner.
#Override
public void run(final RunNotifier notifier)
{
final RunListener listener = new RunListener()
{
#Override
public void testStarted(final Description description) throws Exception
{
// do something before each (non-ignored) Test method is executed
}
#Override
public void testFinished(final Description description) throws Exception
{
// do something after each Test method was performed (failed or successful)
}
// check further listener methods yourself!
};
// install your listener
notifier.addListener(listener);
super.run(notifier);
// and remove it again
notifier.removeListener(listener);
}
Related
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();
}
I made my own JUnit-Runner by implementing org.junit.runner.Runner, so that I can run my UnitTests with them using the #RunWith-Annotation.
It lookes somewhat like this:
public class MyRunner extends Runner {
private Context myContext;
myContext.init();
private final BlockJUnit4ClassRunner runner;
public MyRunner(final Class<?> clazz) throws InitializationError {
myContext = new Context();
runner = new BlockJUnit4ClassRunner(clazz);
}
#Override
public void run(final RunNotifier notifier) {
runner.run(notifier);
}
#Override
public Description getDescription() {
return runner.getDescription();
}
public void filter(final Filter filter) throws NoTestsRemainException {
runner.filter(filter);
}
}
To clean up resources, I have to shut down MyContext by calling MyContext.close(). Where should I invoke this so that my resources are cleand up after the tests have run?
I'm not sure what you're trying to achive but have you already had a look at JUnit's Rules?
public class MyContextRule extends ExternalResource {
private final Context myContext;
public MyContextRule() {
myContext = new Context();
}
#Override
protected void before() throws Throwable {
myContext.init();
}
#Override
protected void after() {
myContext.close();
}
}
Usage:
public class MyTest {
#ClassRule
public static MyContextRule contextRule = new MyContextRule();
//...
}
JUnit Rules advantage over Runners is that you can have multiple of them, while you only can have one runner.
So, your custom Rule could be used with any runner that may be introduced by a random testframework that you may come across in the future...
Where should I invoke this so that my resources are cleand up after
the tests have run ?
UPDATED MY ANSWER, you can use org.junit.runner.notification.RunListener as shown below:
(1) Create your own RunListener class:
public class MyRunnerListener extends RunListener {
private Context context;
public MyRunnerListener(Context context) {
this.context = context;
}
void testRunFinished(Result result) {
context.close();
}
}
(2) Use the MyRunnerListener inside MyRunner :
public class MyRunner extends Runner {
private Context myContext;
MyRunnerListener runnerListener;
private final BlockJUnit4ClassRunner runner;
public MyRunner(final Class<?> clazz) throws InitializationError {
myContext = new Context();
myContext.init();
runnerListener = new MyRunnerListener(myContext);
runner = new BlockJUnit4ClassRunner(clazz);
}
#Override
public void run(final RunNotifier notifier) {
notifier.addListener(runnerListener);
runner.run(notifier);
}
#Override
public Description getDescription() {
return runner.getDescription();
}
public void filter(final Filter filter) throws NoTestsRemainException {
runner.filter(filter);
}
}
P.S.: If you don't want to use the Runner, then you can follow the answer from Markus (which uses TestRule, NOT TestRunner).
I have two class
public class xyzTest {
#Test
public void TestP1TUNG557(){
TestHelper.excuteTestcase(TUNG557);
Assert.assertTrue(TestHelper.TestResult);
}
#Test
public void TestP1TUNG559(){
TestHelper.excuteTestcase(TUNG559);
Assert.assertTrue(TestHelper.TestResult);
}
#Test
public void TestP0TUNG558(){
TestHelper.excuteTestcase(TUNG558);
Assert.assertTrue(TestHelper.TestResult);
}
}
public class TestHelper {
public excuteTestcase(String abc)
{
process(abc)
}
int TotalTescase(String pattern, Class testNGclass)
{
How to write here..? plz help
}
}
suppose if have called TotalTescase(String TestPO, Class xyzTest), it should return 1 and if have called TotalTescase(String TestP1, Class xyzTest) it should return 2.
If This is possible to get total test case like this ,plz help me or provide me some link
I have searched but i couldnt find. help me
You can use reflection technique to find out the matching methods in the supplied class like:
public int TotalTescase(String pattern, Class<?> testNGclass) throws ClassNotFoundException
{
int count = 0;
testNGclass.getClass();
Class<?> className = Class.forName(testNGclass.getName());
Method[] methods = className.getMethods();
for(int i=0; i<methods.length; i++)
{
String methodName = methods[i].getName();
System.out.println("Method Name: "+methodName);
if(methodName.contains(pattern))
{
count++;
}
}
return count;
}
In dry run try to implement IInvokedMethodListener and override beforeInvocation method
public class Test implements IInvokedMethodListener
{
static int testcount=0;
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
testcount=testcount+method.getTestMethod().getInvocationCount();
}
#Override
public void onStart(ISuite suite) {
// TODO Auto-generated method stub
}
#Override
public void onFinish(ISuite suite) {
System.out.println(testcount);
}
}
I'm using a multiplayer Game Client that's called AppWarp (http://appwarp.shephertz.com), where you can add event listeners to be called back when event's happen, let's assume we'll be talking about the Connection Listener, where you need to implement this interface:
public interface ConnectionRequestListener {
void onConnectDone(ConnectEvent var1);
void onDisconnectDone(ConnectEvent var1);
void onInitUDPDone(byte var1);
}
My goal here is to mainly create a Reactive version of this client to be used in my Apps Internally instead of using the Client itself directly (I'll also rely on interfaces later instead of just depending on the WarpClient itself as in the example, but that's not the important point, please read my question at the very end).
So what I did is as follows:
1) I introduced a new event, named it RxConnectionEvent (Which mainly groups Connection-Related events) as follows:
public class RxConnectionEvent {
// This is the original connection event from the source client
private final ConnectEvent connectEvent;
// this is to identify if it was Connection / Disconnection
private final int eventType;
public RxConnectionEvent(ConnectEvent connectEvent, int eventType) {
this.connectEvent = connectEvent;
this.eventType = eventType;
}
public ConnectEvent getConnectEvent() {
return connectEvent;
}
public int getEventType() {
return eventType;
}
}
2) Created some event types as follows:
public class RxEventType {
// Connection Events
public final static int CONNECTION_CONNECTED = 20;
public final static int CONNECTION_DISCONNECTED = 30;
}
3) Created the following observable which emits my new RxConnectionEvent
import com.shephertz.app42.gaming.multiplayer.client.WarpClient;
import com.shephertz.app42.gaming.multiplayer.client.events.ConnectEvent;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.subscriptions.Subscriptions;
public class ConnectionObservable extends BaseObservable<RxConnectionEvent> {
private ConnectionRequestListener connectionListener;
// This is going to be called from my ReactiveWarpClient (Factory) Later.
public static Observable<RxConnectionEvent> createConnectionListener(WarpClient warpClient) {
return Observable.create(new ConnectionObservable(warpClient));
}
private ConnectionObservable(WarpClient warpClient) {
super(warpClient);
}
#Override
public void call(final Subscriber<? super RxConnectionEvent> subscriber) {
subscriber.onStart();
connectionListener = new ConnectionRequestListener() {
#Override
public void onConnectDone(ConnectEvent connectEvent) {
super.onConnectDone(connectEvent);
callback(new RxConnectionEvent(connectEvent, RxEventType.CONNECTION_CONNECTED));
}
#Override
public void onDisconnectDone(ConnectEvent connectEvent) {
super.onDisconnectDone(connectEvent);
callback(new RxConnectionEvent(connectEvent, RxEventType.CONNECTION_DISCONNECTED));
}
// not interested in this method (for now)
#Override
public void onInitUDPDone(byte var1) { }
private void callback(RxConnectionEvent rxConnectionEvent)
{
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(rxConnectionEvent);
} else {
warpClient.removeConnectionRequestListener(connectionListener);
}
}
};
warpClient.addConnectionRequestListener(connectionListener);
subscriber.add(Subscriptions.create(new Action0() {
#Override
public void call() {
onUnsubscribed(warpClient);
}
}));
}
#Override
protected void onUnsubscribed(WarpClient warpClient) {
warpClient.removeConnectionRequestListener(connectionListener);
}
}
4) and finally my BaseObservable looks like the following:
public abstract class BaseObservable<T> implements Observable.OnSubscribe<T> {
protected WarpClient warpClient;
protected BaseObservable (WarpClient warpClient)
{
this.warpClient = warpClient;
}
#Override
public abstract void call(Subscriber<? super T> subscriber);
protected abstract void onUnsubscribed(WarpClient warpClient);
}
My question is mainly: is my implementation above correct or should I instead create separate observable for each event, but if so, this client has more than 40-50 events do I have to create separate observable for each event?
I also use the code above as follows (used it in a simple "non-final" integration test):
public void testConnectDisconnect() {
connectionSubscription = reactiveWarpClient.createOnConnectObservable(client)
.subscribe(new Action1<RxConnectionEvent>() {
#Override
public void call(RxConnectionEvent rxEvent) {
assertEquals(WarpResponseResultCode.SUCCESS, rxEvent.getConnectEvent().getResult());
if (rxEvent.getEventType() == RxEventType.CONNECTION_CONNECTED) {
connectionStatus = connectionStatus | 0b0001;
client.disconnect();
} else {
connectionStatus = connectionStatus | 0b0010;
connectionSubscription.unsubscribe();
haltExecution = true;
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
fail("Unexpected error: " + throwable.getMessage());
haltExecution = true;
}
});
client.connectWithUserName("test user");
waitForSomeTime();
assertEquals(0b0011, connectionStatus);
assertEquals(true, connectionSubscription.isUnsubscribed());
}
I suggest you avoid extending the BaseObservable directly since it's very error prone. Instead, try using the tools Rx itself gives you to create your observable.
The easiest solution is using a PublishSubject, which is both an Observable and a Subscriber. The listener simply needs to invoke the subject's onNext, and the subject will emit the event. Here's a simplified working example:
public class PublishSubjectWarpperDemo {
public interface ConnectionRequestListener {
void onConnectDone();
void onDisconnectDone();
void onInitUDPDone();
}
public static class RxConnectionEvent {
private int type;
public RxConnectionEvent(int type) {
this.type = type;
}
public int getType() {
return type;
}
public String toString() {
return "Event of Type " + type;
}
}
public static class SimpleCallbackWrapper {
private final PublishSubject<RxConnectionEvent> subject = PublishSubject.create();
public ConnectionRequestListener getListener() {
return new ConnectionRequestListener() {
#Override
public void onConnectDone() {
subject.onNext(new RxConnectionEvent(1));
}
#Override
public void onDisconnectDone() {
subject.onNext(new RxConnectionEvent(2));
}
#Override
public void onInitUDPDone() {
subject.onNext(new RxConnectionEvent(3));
}
};
}
public Observable<RxConnectionEvent> getObservable() {
return subject;
}
}
public static void main(String[] args) throws IOException {
SimpleCallbackWrapper myWrapper = new SimpleCallbackWrapper();
ConnectionRequestListener listner = myWrapper.getListener();// Get the listener and attach it to the game here.
myWrapper.getObservable().observeOn(Schedulers.newThread()).subscribe(event -> System.out.println(event));
listner.onConnectDone(); // Call the listener a few times, the observable should print the event
listner.onDisconnectDone();
listner.onInitUDPDone();
System.in.read(); // Wait for enter
}
}
A more complex solution would be to use one of the onSubscribe implementations to create an observable using Observable.create(). For example AsyncOnSubscibe. This solution has the benefit of handling backperssure properly, so your event subscriber doesn't become overwhelmed with events. But in your case, that sounds like an unlikely scenario, so the added complexity is probably not worth it.
I try to use different instances for my tests but the first one is always used.
During the second test, it's the content of the first instance that is displayed.
I don't know where to look for.
public class MyActivityTest extends
ActivityInstrumentationTestCase2<MyActivity> {
private Solo solo;
public MyActivityTest() {
super(MyActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
Authentication.setSessionId("mysessionid", this.getInstrumentation()
.getTargetContext().getApplicationContext());
solo = new Solo(getInstrumentation(), getActivity());
}
public void testFailFetching() {
CommunicationFactory.setInstance(MyActivityData.FALSE_QUIZCOMM_DEFAULT);
//some Solo tests
}
public void testSucceedFetching() {
CommunicationFactory.setInstance(MyActivity.CORRECT_QUIZCOMM_DEFAULT);
//some Solo tests
}
#Override
protected void tearDown() throws Exception {
CommunicationFactory.setInstance(null);
super.tearDown();
}
}
The setUp() method will be called before each test. Provided it completes without throwing an exception (which presumably would abort your tests anyway), your solo variable is being reconstructed for each test. The follow test code demonstrates this:
public class ExampleTest extends TestCase {
private static int num = 1;
private Foo foo;
#Override
protected void setUp() throws Exception {
super.setUp();
foo = new Foo(num++);
}
public void testA() {
foo.printNum();
}
public void testB() {
foo.printNum();
}
private static class Foo {
private final int num;
public Foo(int num) {
this.num = num;
}
public void printNum() {
System.out.println(num);
}
}
}
This prints:
1
2
It's possible the Solo objects equal each other in the separate tests. But they won't be the same object.