Mock a singleton method call from constructor - android

I want to mock the singleton class method, which was called from the constructor.
class client {
client(String s1, Strings s2, Context ctx) {
getInstance().init(ctx);
}
ConfigurationManage getInstance() {
return ConfigurationManager.getInstance();
}
}
How can i mock the getInstance() when this function was called from constructor.
How do mock this function in my test class?
My test class is below:
class clientTest() {
#Test
Public void test(){
ConfigurationManager instance = mock(ConfigurationManager.class)
Client client = new Client("str1", "str2", mock(Context.class))
}
}
How could i mock the getInstance() while calling this from constructor.
Could anyone please help me out on this.

Related

Actual invocation has different arguments Unit Presenter

I create a unit test for my Presenter. My Presenter implements Listener callback if successfully load data from API (use Interactor):
PresenterTest.java
public class MainContactPresenterTest {
#Mock LoadContactInteractor loadContactInteractor;
#Mock ApiService apiService;
#Mock LoadContactView loadContactView;
#Mock ContactRepository contactRepository;
#Mock LoadContactInteractor.OnLoadDataFinishedListener listener;
#InjectMocks MainContactPresenterImpl presenter;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getContactLists() {
// given
// when
presenter.fetchRemoteContacts();
// then
Mockito.verify(loadContactInteractor).onLoadData(listener);
}
}
Here is my Presenter:
public class MainContactPresenterImpl implements MainContactPresenter,
LoadContactInteractor.OnLoadDataFinishedListener {
private LoadContactView loadContactView;
private LoadContactInteractor loadContactInteractor;
private ContactRepository contactRepository;
#Inject
public MainContactPresenterImpl(LoadContactInteractor loadContactInteractor,
#NonNull LoadContactView loadContactView,
ContactRepository contactRepository) {
this.loadContactView = loadContactView;
this.loadContactInteractor = loadContactInteractor;
this.contactRepository = contactRepository;
}
#Override
public void onSuccessLoad(List<Contact> contacts) {
loadContactView.saveDataToLocalStorage(contacts);
}
#Override
public void onErrorLoad() {
loadContactView.dismissProgress();
loadContactView.showErrorMessage();
}
#Override
public void preCheckCacheData() {
if (contactRepository.getContactCount() == 0) {
// Load contacts from Server
fetchRemoteContacts();
} else {
fetchLocalContacts();
}
}
#Override
public void fetchRemoteContacts() {
loadContactView.showProgress();
loadContactInteractor.onLoadData(this);
}
}
But when I ran test, I got the mocking parameter in verify not match.
I got my presenter that have to be an argument. Not the listener.
Argument(s) are different! Wanted:
loadContactInteractor.onLoadData(
listener
);
Actual invocation has different arguments:
loadContactInteractor.onLoadData(
fanjavaid.gojek.com.contacts.presenter.MainContactPresenterImpl#1757cd72
);
How to handle that? Thank you
You are creating a mock...
#Mock LoadContactInteractor.OnLoadDataFinishedListener listener;
...and then you don't use it ever again and act suprised when verify tells you, that it wasn't actually used. Why? Of course it wasn't used, since you never use it anywhere, so how should your classes know to use that mock object?
Your MainContactPresenterImpl does not use an OnLoadDataFinishedListener as an external dependency (then your could perhaps inject it via #InjectMocks), it is itself such a listener and thus mocking another listener makes no sense here.
In other words, MainContactPresenterImpl has no OnLoadDataFinishedListener field, so Mockito is of course not capable of injecting something in this non-existing field. For something like this to work, you would need to add such a field and then use the content of that field when calling your onLoadData method.
The only invocation of your method is here...
loadContactInteractor.onLoadData(this);
And what is this in that context? It's the MainContactPresenterImpl object that contains the method, in other words, your presenter.
So, what will work is...
Mockito.verify(loadContactInteractor).onLoadData(presenter);

Xamarin Dependency Service with context

I have a problem with the dependency services for implementing features that depends of the plattorm. I need what my implementation on Android receive a Context object to do the task. How can I do it?
This is my code:
1) On PCL:
public interface ICallService
{
List<string> GetContacts();
}
2) On Android Project:
[assembly: Dependency(typeof(CallService))]
namespace DEMOBLOBS.Droid.DependencyServicesPruebas
{
public class CallService : ICallService
{
public static void Init() { }
public List<string> GetContacts()
{
AT THIS POINT I NEED THE CONTEXT OBJECT!
}
}
}
The constructor of Call Service class does not have any parameter. Maybe I can I pass the Context object like parameter in some way?
Can you help me, please?
you could try answer from https://forums.xamarin.com/discussion/106938/context-is-obsolete-as-of-version-2-5
internal static MainActivity Instance { get; private set; }
protected override void OnCreate(Bundle bundle)
{
Instance = this;
// Forms initialization here...
}
//later where you need it:
var context = MainActivity.Instance;

Unit test static method with dependency

I have not much experience in unit testing, especially with Mockito and now I have encountered the following situation.
class A {
void setField(String obj) {
}
Object execute() {
throw new RuntimeException("Meh!");
}
}
class B {
//function to be tested
static Object someMethod() {
A a = new A();
a.setField("test");
Object response = a.execute();
//logic here
return response;
}
}
class BTest() {
A aInstance = mock(A.class);
#Test
public void test_someMethod_when_exec_returns_X() {
when(aInstance.execute()).thenReturns("X");// doesn’t work
assertTrue("X", B.someMethod());
}
}
I want to test the someMethod static method when a.execute() returns specific value.
I know, I can create a mock object of A and pass it to someMethod function, which is not a good solution as I should change the signature of someMethod.
What is the correct solution in this case?
If you check out PowerMockito's documentation you'll realize that the following is what you need:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;
// execute the test with the appropriate runner
#RunWith(PowerMockRunner.class)
// prepare B for instrumentation so we can hack stuff inside
#PrepareForTest(B.class)
public class MyTest {
#Test
public void bShouldCallA() throws Exception {
// create a mock for A and configure its behaviour
A aMock = mock(A.class);
when(aMock.execute()).thenReturn("X");
// make sure that when A's constructor is called in the static method, the mock above is returned
whenNew(A.class).withNoArguments().thenReturn(aMock);
// do the actual invocation
Object actualResult = B.someMethod();
// check result and interactions
assertEquals("X", actualResult);
verify(aMock).setField("test");
}
}
As I mentioned, the PowerMockito doesn't work in android, you can just mock android object with that. And here comes engineering solution :)
Factory class to create object A.
public class AFactory {
static private AFactory sInsntance = new AFactory();
public static AFactory createObject() {
return sInsntance.createInternally();
}
protected TMMethodBuilder createInternally() {
return new A();
}
//This function is only for testing, in order to inject factory
#Deprecated
public static void setFactory(AFactory mock) {
sInsntance = mock;
}
}
And create object A:
A a = AFactory.createObject();
In Test project extend AFactory and override createInternally() method to return mocked object.
public class AFactoryTest extends AFactory {
private static A a = mock(A.class);
#Override
protected TMMethodBuilder createInternally() {
return a;
}
}
So in test class just do the following:
factory = new AFactoryTest();
a = factory.createInternally();
AFactory.setFactory(factory);
//
when(..).thenReturn();

Dagger not initializing injected field in Android

Started introducing Dagger into my App and I'm having problems getting a very basic field initialized. Here's a reduced version of my code:
#Inject public DaggerUtils daggerUtils;
public class AppState extends Application {
#Override
public void onCreate() {
super.onCreate();
// Set up Dagger
AppModule appModule = new AppModule();
mObjectGraph.create(appModule);
daggerUtils.print();
}
}
Module used:
#Module(
injects = { AppState.class}
)
public class AppModule {
// This provides method is commented out because from what I can understand from the Dagger documentation
// Dagger should automatically take care of calling the constructor I have provided
// with the #Inject annotation. I have tried commenting this out as well and it still
// fails.
//#Provides
//DaggerUtils provideDaggerUtils() {
// return new DaggerUtils();
//}
}
Basic util class:
public class DaggerUtils {
#Inject
public DaggerUtils() {
}
public void print(){
Logger.e("Dagger", "printed instantiated");
}
}
So from what I understand because I have the #Inject annotation before the DaggerUtils constructor and the #Inject annotation before the DaggerUtils instance I'm using in my AppState class, Dagger should take care of initializing the DaggerUtils instance without me having to call the constructor. However it keeps giving me an NullPointerException when I try to call daggerUtils.print() (Line 12 in AppState class). Why is dagger not initializing DaggerUtils? I feel like I'm missing something very basic here. I've also tried using the #Provides method commented out in the AppModule to provide an instantiated DaggerUtils but it still isn't working.
I had same problem this evening.
For every class, who needs injection you must call:
mObjectGraph.create(appModule).inject(this);
That is usefull to create inject method in Application.
public void inject(Object object) {
mObjectGraph.inject(object);
}

Roboguice 2.0 (android): POJO injection error (always null)

My base POJO class:
public class BaseDao {
public BaseDao() {
}
// ...
}
My extends POJO class:
public class KelvinDao extends BaseDao {
public KelvinDao () {
super();
}
// ...
}
I want to use KelvinDao in a service like that:
public class HanKelvinHandler extends HttpRequestHandler {
#Inject
private KelvinDao mKelvinDao;
public void treatGet() {
mKelvinDao.blabla(); !!! mKelvinDao is always NULL
}
It's really simple but it doesn't work :(
Thank you guys for your help!
How are you creating HanKelvinHandler? If you're doing it within a subclass of a RoboGuice class, such as RoboActivity, then it should just work. Example:
public class MyActivity extends RoboActivity
{
#Inject
private HanKelvinHandler m_handler;
[...]
}
Otherwise (i.e., you're creating it within another POJO), you're in regular Guice land, and I believe you will need to use the injector to get an instance of it. Example:
public class MyClass
{
public void doSomething()
{
Injector injector = Guice.createInjector( new YourGuiceBindings() );
HanKelvinHandler handler = injector.getInstance( HanKelvinHandler.class );
handler.treatGet(); // mKelvinDao should be good now
}
}
If you haven't seen the use of the injector before, or you don't know what to put for YourGuiceBindings(), then you may need to read the following:
https://github.com/roboguice/roboguice/wiki/Simple-Custom-Binding
https://code.google.com/p/google-guice/wiki/GettingStarted
It seems like there should be a way to do this without using the injector, but I don't know.

Categories

Resources