What is the best way to test Awareness Api Accuracy? - android

I'm using Awareness API, and wondering, what is the best way to test is during development, on a device (not an emulator)?
I want to emulate to test its accuracy
location / activity / weather
changes for example.
How can I achieve it?
Thank you!

Your question is quite general, so I will give the general answer. Basically, you shouldn't test external APIs and libraries, so you should have named this thread differently. What you want to do is to emulate the specific behavior of the API.
You can do it in the following way:
use Dependency Injection library like Dagger and hide API
implementation behind the interface
add library implementation of the interface
add another stub implementation simulating behavior you want to achieve
in Gradle configuration, you can assign proper
implementation of the interface or use flavors functionality to
configure build variants (e.g. awareness-testing, production, etc.)
Remember to exclude Stub class from production build.
I'm not sure about exact implementation, but I'd go, more or less, this way.
Moreover, you can test specific functionalities via unit tests

Related

Question: Databinding not working with runtimeOnly gradle dependncies

Hoping someone can explain why data binding per module seems not work (returns null) when a specific module/s are declared as runtimeOnly vs when it's declared as implementation.
e.g.
Say I've got some feature modules which I want to include or exclude (similar to dynamic feature modules) except I'm not using that right now for other reasons I will not go into, this is more of an experiment. So the idea was to have multiple components detached from the main application that are only made available at runtime, so in other words virtual no coupling between app and any of the add-on features and this works fine until I add data binding into the mix, crashing with a *Binding cannot be null.
The only way I've gotten this setup to work is by switching back from runtimeOnly to implementation and from what I know so far the difference between runtimeOnly and impelentation are on the gradle website:
So my question is why does this happen, does enabling databinding in modules require the module to be configured with implementation? Or perhaps I'm doing it all wrong and have misunderstood the purpose of runtimeOnly.
Thank you in advance, and apologies if the question is not comprehensive enough
implementation: mostly we use implementation configuration. It hides the internal dependency of the module to its consumer to avoid accidental use of any transitive dependency, hence faster compilation and less recompilation.
runtimeOnly: when we want to change or swap the behaviour of the library at runtime (in final build).
In the case of runtimeOnly, you need two dependencies one which will help you to access the code at compile-time and one which will replace/use at runtime.
Example of Runtime:
SLF4J is one of the best examples of runtimeOnly, where we will use slf4j-api as implementation configuration and implementation of slf4j-api (like slf4j-log4j12 or logback-classic, etc) as runtimeOnly configuration.
I have created a post with an in-depth understanding of each one with Working Example: source code
https://medium.com/#gauraw.negi/how-gradle-dependency-configurations-work-underhood-e934906752e5

How to initialize emulated external dependencies in a Kotlin Android UI test

I'll be developing an Android app in Kotlin and I'm trying to figure out how to initialize emulated dependencies. For example, the app will make API calls to a server, obtain the user's location from a location provider, pull down images from a content management system, store data locally in a database and in Android's Shared Preferences, and do math based on the current date/time. Thus there are a lot of external dependencies I want to emulate, including the current date/time so I can verify age calculation, etc.
My goal for testing is just to validate my app's screens using an Android instrumented test. I don't want any dependency on real external systems because testing those systems is the responsibility of the developers of those systems.
While reading Android'd documentation Consider whether to use test doubles, I noticed it offered a good tip: "Tip: Check with the library authors to see if they provide any officially-supported testing infrastructures, such as fakes, that you can reliably depend on." However, the documentation doesn't really explain how to initialize a 3rd party test infrastructure.
Below are what I understand so far about my options, but they all come back to a fundamental thing I don't understand: how does an Android app under test know it should operate in a test mode vs. a production mode?
Mocking such as Mockito or MockK: Mocking seems like a special case of Dependency Injection tailored for testing. The examples I've seen involve testing a class or a method, not a full scale system. The examples typically show how you mock a class and pass it to the class/method under test. But with a full scale system, the test code operates on widgets referenced via Espresso. There is no access to the classes where the logic is. My impression is mocking is for unit testing, not UI testing. But maybe someone can explain how to use mocking for UI testing:
a) Suppose an external dependency is initialized deep in the call stack. If I define a mock in my test code's setup function (e.g. a method annotated with #Before), how do I pass that down to the place in the code that depends on it?
b) I keep reading that mocks don't work in Kotlin because Kotlin defines all classes as final. There seem to be a few work arounds. But does does Google/Android officially recommend one of these (I haven't read it in their documentation).
Dependency Injection such as Dagger 2: If mocking isn't viable for UI testing, then should I use Dependency Injection? From what I understand, it seems Dagger 2 deals with issue 1.a above by defining a top-level Component and a tree of Modules which can provide dependencies at any layer of the stack. For testing, it seems like I would just provide a different Component that emulates the real dependencies.
a) In an Android instrumented test, where do instantiate a Dagger 2 Component designed for testing. How do I make sure that Component is used rather than the Component intended for production?
Prepare before launching test: I can see how I could customize build.gradle to prepare my test environment before my application is launched. For example, I could pass a flag to my app so that when the Application's onCreate() gets called, I can configure my system to prepare emulated dependencies via Dependency Injection, Mocking, or even just a custom implementation. For example, some external dependencies have a test mode where I would need to pass a flag to them so they work in test mode. I'm not clear how that sort of thing reconciles with Dependency Injection or Mock but I guess I could see how I could use those mechanisms as a wrapper to pass the test flag or not. In the following post someone wanted to mock a location provider and to do that they modified their build.gradle file to set things up before the Android test infrastructure started.
How to set Allow Mock Location on Android Device before executing AndroidTest with uiautomator and espresso?
In conclusion, I want to test a Kotlin Android app's UI using Android instrumented test with Espresso but I don't know how to setup the test so that external dependencies use emulation code rather than production code. Should I use mocking, Dependency Injection, or customize via build.gradle? Can someone help me get my thinking on track?
After much searching, I've discovered that the Android ActivityTestRule allows you to defer launching the Activity. This gives the test code time to initialize emulated dependencies as demonstrated in Fast Mocked UI Tests on Android Kotlin.

Mock FingerprintManager in Android tests

Is there a way to simulate or mock FingerprintManager.authenticate()? I want to write instrumented tests for my fingerprint authenticator.
I'm fine if there's a solution with a restriction that the tests can be run either on an emulator or a device. I use JUnit 4.12.
I might suggest that you don't mock it, in the spirit of not mocking things you don't own. What I might suggest instead (from the above link):
The prescription implied by "don't mock what you don't own" is to introduce your own shim/wrapper/adapter around it. This effectively cordons off the dependency to a single place in your codebase and contextualizes it in the consistent and easy-to-use style you're trying to promote within your codebase. If there's anything awkward about how one needs to invoke the dependency (maybe a chaining API, multi-step invocation, repetitive default configuration, etc.), it can be swept under the rug into that common adapter.
This feels like an instance where the humble object pattern might be appropriate.

Trying to fit a "clean architecture" on an iOS app

Recently I’ve been rethinking my android architecture project, trying to adapt it to a more “clean architecture”, specifically, the kind of design suggested by “Uncle Bob”.
Which it involves several layers of abstractions, a nice isolation of responsibilities and a very strong dependency inversion achieved by dependency injection; which, ultimately, leads to a very decoupled-portable system. A perfect candidate to be tested by unit testing and integration testing.
In my android implementation I’ve ended up having three different modules or layers:
-domain: entities, interactors, presenters (pure java module)
-data: (acts as a repository to supply the data to the domain) (android library module)
-presentation: ui related stuff, fragments, activities, views, etc (android application module)
So, I’m trying to figure out what would be the best approach on the iOS ecosystem.
I’ve tried creating a project with multiple targets to achieve the same solution:
-domain: command line target (which seems very weird but I think is the most pure swift target available)
-data: cocoa touch framework
-presentation: cocoa touch framework
With this approach I can use these targets in the way I did with android modules. But the first caveat I’ve found it is that I need to add manually every new file to the dependent target.
But my knowledge is very limited in projects with multiple targets. I mean I’ve never created an iOS application with multiple targets. So I don’t know even if the solution would be use a framework (cocoa touch/cocoa) as a target instead of a command line module for the domain layer.
Any thought would be really appreciate.
Thanks!
Uncle Bob's Clean Architecture absolutely applies to iOS, Swift, and Obj-C. Architecture is language agnostic. Uncle Bob himself codes mostly in Java but in his talks he rarely mentions Java. All his slides do not even show any code. It is an architecture meant to be applied to any project.
Why am I so sure? Because I've studied MVC, MVVM, ReactiveCocoa, and Clean Architecture for 2 years. I like Clean Architecture the best, by far. I tested it by converting 7 Apple sample projects to using the Clean Architecture. I've used this approach exclusively for over a year. It works out better every time.
Some of the benefits are:
Find and fix bugs faster and easier.
Extract business logic from view controllers into interactors.
Extract presentation logic from view controllers into presenters.
Change existing behaviors with confidence with fast and maintainable unit tests.
Write shorter methods with single responsibility.
Decouple class dependencies with clear established boundaries.
We also added a router component so we can use multiple storyboards. No more conflicts.
Writing unit tests is greatly simplified too because I only need to test the methods at the boundaries. I don't need to test private methods. On top of that, I didn't even need any mocking framework because writing your own mocks and stubs becomes trivial.
I've written my experience for my last 2 years studying iOS architecture at Clean Swift I also put together some Xcode templates to generate all the Clean Architecture components to save a ton of time.
UPDATE - To answer #Víctor Albertos's question about dependency injection in the comment below.
This is a really great question and demands a long detailed answer.
Always keep the VIP cycle in mind. In this case, the doSomethingOnLoad() method is not a boundary method. Rather, it is an internal method invoked only within CreateOrderViewController. In unit testing, we test a unit's expected behavior. We give inputs, observe outputs, then compare the outputs with our expectations.
Yes, I could have made doSomethingOnLoad() a private method. But I chose not to. One of the goals of Swift is to make it easy for developers to write code. All the boundary methods are already listed in the input and output protocols. There is really no need to litter the class with extraneous private modifiers.
Now, we do need to test this behavior of "The CreateOrderViewController should do something on load with this request data" somehow, right? How do we test this if we can't invoke doSomethingOnLoad() because it is a private method? You call viewDidLoad(). The viewDidLoad() method is a boundary method. Which boundary? The boundary between the user and view controller! The user did something to the device to make it load another screen. So how do we invoke viewDidLoad() then? You do it like this:
let bundle = NSBundle(forClass: self.dynamicType)
let storyboard = UIStoryboard(name: "Main", bundle: bundle)
let createOrderViewController = storyboard.instantiateViewControllerWithIdentifier("CreateOrderViewController") as! CreateOrderViewController
let view = createOrderViewController.view
Simply calling the createOrderViewController.view property will cause viewDidLoad() to be invoked. I learned this trick a long time ago from someone. But Natasha The Robot also recently mentioned it too.
When we decide what to test, it is very important to only test the boundary methods. If we test every method of a class, the tests become extremely fragile. Every change we make to the code will break many, many tests. A lot of people give up because of this.
Or, think about it this way. When you ask how to mock CreateOrderRequest, first ask if doSomethingOnLoad() is a boundary method that you should write test for. If not, what is? The boundary method is actually viewDidLoad() in this case. The input is "when this view loads." The output is "call this method with this request object."
This is another benefit of using Clean Swift. All your boundary methods are listed at the top of the file under explicitly named protocols CreateOrderViewControllerInput and CreateOrderViewControllerOutput. You don't need to look elsewhere!
Think about what happens if you were to test doSomethingOnLoad(). You mock the request object, then assert that it equals to your expected request object. You are mocking something and comparing it. It's like assert(1, 1) instead of var a=1; assert(a, 1). What's the point? Too many tests. Too fragile.
Now, there is a time when you do mock CreateOrderRequest. After you've verified the correct CreateOrderRequest can be generated by the view controller component. When you test CreateOrderInteractor's doSomething() boundary method, you then mock CreateOrderRequest using interface dependency injection.
In short, unit testing is not about testing every unit of a class. It is about testing the class as a unit.
It is a mindset shift.
Hope that helps!
I have 3 series of draft posts in Wordpress on different topics:
In-depth look at each of the Clean Swift components
How to break up complex business logic into workers and service objects.
Writing tests in Clean Swift iOS architecture
Which one of these do you want to hear more first? Should I bump up the series on testing?
In my opinion Clean Architecture is a set of ideas, rules, principles... to make a code better.
[Android Clean Architecture]
With this approach I can use these targets in the way I did with android modules.
You are able create a target[About](application target or framework target...) but it depends on your needs
If you read Architecting Android...Reloaded from Fernando Cejas
you might have seen that I used android modules for representing each layer involved in the architecture.
A recurring question in discussions was: Why? The answer is simple… Wrong technical decision
The idea is that is not necessary to use some build components to implement Clean Architecture

Mocking framework for use with xamarin android

I am trying to find a mocking framework that works with Xamarin Android. So far I have tried Rhino Mocks and Moq but both depend on System.Web.dll which does not seem to be supported by Xamarin. I have included the System.Web.Services reference to my project with no luck.
So my question is what mocking frameworks out there are compatible with Xamarin projects? This is just for simple mocking not even specific android classes like activities, although one that could combine both would be best.
From what I've observed, there really is no mocking frameworks that work well with Xamarin. On the iOS side, this is mainly due to the inability to use Reflection.Emit because of the code generation restriction imposed by Apple. I realize you're on Android, so that restriction does not apply to you. However, other restrictions arise, like you've found with RhinoMocks. My favorite mocking framework is Moq, but I can't use it with Xamarin because of some of the configuration namespaces that are implemented in .NET, but not in Mono.
So, your best bet is just manual mocks. I know that's not the answer you want to hear, but it seems to be the consensus.
You can use True Fakes (http://truefakes.net) mocking framework to solve your issues. It doesn’t use Reflection.Emit at runtime, but it automatically generates mocks at compile time and add it to assembly where unit-tests are. This allows you to use True Fakes for writing unit tests with fully isolated system under test for Xamarin.Android and Xamarin.iOS and running them directly on the device!
You can add it to your project via NuGet (https://www.nuget.org/packages/TrueFakes/).
Please see more information about True Fakes at http://truefakes.net.
PS. I’m developer of True Fakes mocking framework.
I've been using a mock generator called PCLMock.
I had to fork it to get it working with .netstandard, you can give it a go by cloning it and building it from here:
https://github.com/pellet/PCLMock
It works by generating code before compile time, therefore not needing the reflection apis missing in AOT compiled xamarin projects.
Otherwise you could always go functional style and pass in your dependencies as delegates/Funcs, this way you don't need to generate mocks for interfaces, you can use a builder class for injecting mocked out lambdas in unit tests.

Categories

Resources