ButterKnife error while running TestCases in androidstudio - java

I have created one test case in androidTest folder as MyHomeActivityTest.Java
in
/app/src/androidTest/java/MyHomeActivityTest.java
And I have one HomeActivity.java class in
/app/src/main/java/HomeActivity.java
In my HomeActivity.java class i am using butterknife for view-injection. I am running the test cases for HomeActivity in MyHomeActivityTest.java.
But when i am running the test cases the tests are running fine but getting NoClassDefFound Error for butterknife.
My Project classes are
MyHomeActivityTest.java
public class HomeActivityTest extends ActivityInstrumentationTestCase2<HomeActivity> {
private Solo solo;
public HomeActivityTest() {
super(HomeActivity.class);
}
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation());
getActivity();
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
public void testRun() {
solo.assertCurrentActivity("Home activity class",HomeActivity.class);
final LinearLayout homeScreen =
(LinearLayout) solo.getCurrentActivity().findViewById(R.id.home_screen);
assertEquals(View.GONE, homeScreen.getVisibility());
}
}
build.gradle
dependencies{
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.jakewharton:butterknife:5.1.1'
compile 'com.squareup.picasso:picasso:1.1.1'
androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.1'
}
As soon i am running the MyHomeActivityTest class it's giving me NoClassDefFoundError since the super class of this is HomeActivity.class which is using butterKnife.

Try to add ButterKnife Dependencies to your AndroidTest folder.

Related

Cannot resolve symbol 'AuthUI' , Cannot resolve symbol 'FirebaseAuth'

Im trying to create sign in option using FirebaseUi getting this errors
Cannot resolve symbol 'AuthUI' ,
Cannot resolve symbol 'FirebaseAuth'
This is the code:
public class SplashScreenActivity extends AppCompatActivity {
private final static int LOGIN_REQUEST_CODE = 7898;
private List<AuthUI.IdpConfig> providers;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.Authstatetistener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delaySplashScreen();
init();
}
private void init(){
providers = Arrays.asList(
new AuthUi.IdpConfig.PhoneBuilder().build(),
new AuthUi.IdpConfig.GoogleBuilder().build());
}
#SuppressLint("CheckResult")
private void delaySplashScreen(){
Completable.timer(5, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).subscribe(() -> Toast.makeText(SplashScreenActivity.this, "Splash Screen Done", Toast.LENGTH_SHORT).show());
}
}
I'm using this Dependencies
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-auth:21.1.0'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
implementation 'com.firebaseui:firebase-ui-auth:8.0.2'
}
Help me to fix this problem why AuthUi is not working here as well as FirebaseAuth.
Please give me some suggetions how to solve this.
The error message "Cannot resolve symbol 'AuthUI'" and "Cannot resolve symbol 'FirebaseAuth'" is indicating that the class or interface is not recognized by the compiler.
This is likely because the required library has not been imported in your project. To fix this issue, you need to import the Firebase UI library and Firebase Auth library to your project.
Add the following to your build.gradle (Module: app) file:
dependencies {
implementation 'com.firebaseui:firebase-ui-auth:6.2.2'
implementation 'com.google.firebase:firebase-auth:20.0.0'
}
After adding the dependencies, sync your project to download the libraries. Then, import the required classes in your code:
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
This should resolve the "Cannot resolve symbol" errors.

Running JBehave with Junit 5 Jupiter

I'm trying to get some JUnit 4 based JBehave tests running on JUnit 5. In my project I have a single test class for all stories JBehaveTest.
When I run it as a JUnit 5 test JUnit doesn't see any tests. I modified the #Test annotations to their Jupiter equivalents, I changed the assertTrue and assertFalse to their equivalents, etc.
The JUnit 4 test is annotated with a #RunWith annotation, which in JUnit 5 should be a #ExtendWith annotation if I understood correctly. Unfortunately JBehave is not a JUnit 5 extension, so it won't compile.
Can JBehave be used with JUnit 5, and if so, how?
#RunWith(AnnotatedEmbedderRunner.class)
#UsingEmbedder(embedder = Embedder.class, verboseFailures = true, ignoreFailureInStories = false, generateViewAfterStories = true)
public class JBehaveTest implements Embeddable {
private Embedder embedder;
private DotStoryReporter dot = new DotStoryReporter();
private Stage primaryStage;
#Before
public void createStage() throws TimeoutException {
Locale locale = new Locale("fa", "IR");
Locale.setDefault(locale);
primaryStage = FxToolkit.registerPrimaryStage();
}
#Override
#Test
public void run() throws Throwable {
embedder.runStoriesAsPaths(new StoryFinder().findPaths("src/test/resources", Collections.singletonList("**/*.story"), Collections.<String>emptyList()));
}
#Override
public void useEmbedder(Embedder embedder) {
this.embedder = embedder;
MostUsefulConfiguration configuration = new MostUsefulConfiguration();
Steps steps = new Steps();
configuration.useStoryReporterBuilder(
new StoryReporterBuilder()
.withCodeLocation(CodeLocations.codeLocationFromClass(JBehaveTest.class))
.withDefaultFormats()
.withReporters(dot, new MyStoryReporter(new File("test"), steps))
.withFormats(Format.HTML, Format.TXT)
.withFailureTrace(true)
.withFailureTraceCompression(false));
configuration.useStepdocReporter(new DetailedStepReporter());
embedder.useStepsFactory(new InstanceStepsFactory(configuration, steps));
embedder.useConfiguration(configuration);
}
The Gradle test dependencies are:
testCompile 'org.junit.jupiter:junit-jupiter-api:5.2.0'
testCompile 'org.mockito:mockito-core:2.18.3'
testRuntime 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
testRuntime 'org.junit.platform:junit-platform-launcher:1.2.0'
testCompile 'org.testfx:testfx-core:4.0.+'
testCompile 'org.testfx:testfx-junit5:4.0.+'
testCompile 'org.jbehave:jbehave-core:4.3.2'
testCompile 'de.codecentric:jbehave-junit-runner:1.2.0'

Error: #dagger.android.ContributesAndroidInjector was used, but dagger.android.processor.AndroidProcessor was not found

I am trying to setup Dagger 2.12 and I'm getting this error:
error: #dagger.android.ContributesAndroidInjector was used, but dagger.android.processor.AndroidProcessor was not found on the processor path
Here's how I've configured Dagger:
My Application class:
public final class App extends android.app.Application implements HasActivityInjector {
#Inject
DispatchingAndroidInjector<Activity> activityInjector;
#Override
public void onCreate() {
super.onCreate();
DaggerAppComponent.builder().build().inject(this);
}
#Override
public AndroidInjector<Activity> activityInjector() {
return activityInjector;
}
}
ActivityBindingModule:
#Module
public abstract class ActivityBindingModule {
#ContributesAndroidInjector(modules = SearchActivityModule.class)
abstract SearchActivity searchActivity();
}
SearchActivityModule:
#Module
public class SearchActivityModule {
#Provides
public SearchActivityDelegate getDelegate(SearchActivity searchActivity) {
return searchActivity;
}
#Provides
public SearchActivityPresenter providePresenter(SearchActivity searchActivity) {
return new SearchActivityPresenter(new OtherDependency(), searchActivity);
}
}
AppModule:
#Module(includes = { AndroidInjectionModule.class, ActivityBindingModule.class })
public abstract class AppModule {
}
Does anyone know what could be causing this error?
Go to your module level build.gradle, under
annotationProcessor 'com.google.dagger:dagger-android-processor:[YOUR VERSION NUMBER]',
add:
kapt 'com.google.dagger:dagger-android-processor:[YOUR VERSION NUMBER]'.
the only solution for me was using old version of dagger (2.16)
kotlin version : 1.2.71
// dagger
implementation 'com.google.dagger:dagger-android:2.16'
implementation 'com.google.dagger:dagger-android-support:2.16'
kapt "com.google.dagger:dagger-compiler:2.16"
kapt "com.google.dagger:dagger-android-processor:2.16"
Probably you would have missed the following dependency.
annotationProcessor 'com.google.dagger:dagger-android-processor:' + yourDaggerVersion
For Java
Add this to your build.gradle
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
For Kotlin
Add this to your build.gradle
apply plugin: 'kotlin-kapt'
kapt "com.google.dagger:dagger-android-processor:$dagger_version"

Dagger 2 "Dagger" prefix component not able to compile? auto generated class

Im trying to use Dagger 2 on android. I previously had it working and i had an appModule injecting dependencies into specific classes in the app. My Issue is that iam getting the error
Error:(14, 55) error: cannot find symbol class DaggerAppComponent
which attempting to import. this is an autogenerated class
below are my Dagger specific dependencies in my build.gradle file
compile 'com.google.dagger:dagger-compiler:2.0.2'
compile 'com.google.dagger:dagger:2.0.2'
provided 'javax.annotation:jsr250-api:1.0'
Ive tried cleaning and rebuilding the app numerous times but the class wont generate. Ive also tried using
compile 'org.glassfish:javax.annotation:10.0-b28'
for my annotations but Iam having no luck still? If anyone can help me out id appreciate. Its kind of difficult to see exactly what is going on for me at present? Thanks
EDIT: Component code
this was working before and i just added 1 extra class to inject into?
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(RegHelper reghelper);
void inject(headerFooterRecViewAdapter headadapter);
void inject(SectionListExampleActivity seclistactivity);
}
This did the trick for me with the (current) latest dagger dependecies.
`dependencies{
...
compile 'com.google.dagger:dagger:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
annotationProcessor "com.google.dagger:dagger-compiler:2.11"
}`
Please add
apt 'com.google.dagger:dagger-compiler:2.x'
to your app build.gradle file
Setting up a stand-alone project in Android Studio 2.3, I updated the default gradle files as follows to get the generated Component file. Added lines have comment // dagger2 addition
PROJECT build.gradle:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
// dagger2 addition
classpath 'com.android.tools.build:gradle:1.0.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.+'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
// dagger2 addition
mavenCentral()
maven{
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
APP MODULE build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' // dagger2 addition
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.demo.dagger2demo"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
// dagger2 addition
compile 'com.google.dagger:dagger:2.+'
apt "com.google.dagger:dagger-compiler:2.+"
}
You need to install this plugin https://bitbucket.org/hvisser/android-apt in order for Android Studio to see the Dagger Components.
I was having a similar issue with Dagger 2. I had an AppComponent and an ActivityComponent (being a subcomponent). And as soon as I would add a new inject() function in the AppComponent, I would get the above errors.
There was more errors besides the 'cannot find symbol' error but they were very vague and I couldn't debug my issues. After digging and researching stackoverflow and different tutorials, I realized I was using Dagger incorrectly. Specifically the way my AppComponent and ActivityComponent was setup.
I was under the assumption that I could inject my 'Activity' or 'Fragment' with both my AppComponent and ActivityComponent. This turned out to be wrong, at least I found out that it wasn't the right way of using Dagger.
My Solution:
AppComponent
#Singleton
#Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MyApp application);
void inject(ContextHelper contextHelper);
// for exports
MyApp application();
PrefsHelper prefsHelper();
}
App Module
#Module
public class AppModule {
private final MyApp application;
public AppModule(MyApp application) {
this.application = application;
}
#Provides #Singleton
public MyApp application() {
return this.application;
}
#Provides #Singleton
public PrefsHelper providePrefsHelper() {
PrefsHelper prefsHelper = new PrefsHelper(application);
return prefsHelper;
}
}
ActivityComponent
#ActivityScope
#Component (dependencies = {AppComponent.class}, modules = {ActivityModule.class})
public interface ActivityComponent {
void inject(MainActivity activity);
void inject(OtherActivity activity);
void inject(SomeFragment fragment);
}
ActivityModule
#Module
public class ActivityModule {
private final MyActivity activity;
public ActivityModule(MyActivity activity) {
this.activity = activity;
}
#Provides #ActivityScope
public ContextHelper provideContextHelper(MyApp application) {
// My ContextHelper depends on certain things from AppModule
// So I call appComponent.inject(contextHelper)
AppComponent appComponent = application.getAppComponent();
ContextHelper contextHelper = new ContextHelper(activity);
appComponent.inject(contextHelper);
return contextHelper;
}
}
Application
public class MyApp extends Application {
private AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
initializeDepInj();
}
private void initializeDepInj() {
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
}
public LockAppComponent getAppComponent() {
return appComponent;
}
}
Activity
public class MainActivity extends AppCompatActivity {
// I get it from ActivityModule
#Inject
ContextHelper contextHelper;
// I get it from AppModule
#Inject
PrefsHelper prefsHelper;
ActivityComponent component;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupInjection();
}
protected void setupInjection() {
MyApp application = (MyApp) getApplication();
component = DaggerActivityComponent.builder()
.appComponent(application.getAppComponent())
.activityModule(new ActivityModule(this))
.build();
component.inject(this);
// I was also doing the following snippet
// but it's not the correct way since the ActivityComponent depends
// on AppComponent and therefore ActivityComponent is the only
// component that I should inject() with and I'll still get classes
// that are provided by the AppComponent/AppModule
// application.getAppComponent().inject(this); // this is unneccessary
}
public ContextHelper getContextHelper() {
return contextHelper;
}
}
I don't know if it directly resolves your issue but it should at least shed some light on how to use Dagger properly.
Hope it helps.
I had the same problem on my setup, Android Studio 2.2 within the following application class:
public class NetApp extends Application {
private NetComponent mNetComponent;
#Override
public void onCreate() {
super.onCreate();
// Dagger%COMPONENT_NAME%
mNetComponent = DaggerNetComponent.builder()
// list of modules that are part of this component need to be created here too
.appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
.netModule(new NetModule("https://api.github.com"))
.build();
// If a Dagger 2 component does not have any constructor arguments for any of its modules,
// then we can use .create() as a shortcut instead:
// mNetComponent = com.codepath.dagger.components.DaggerNetComponent.create();
}
public NetComponent getNetComponent() {
return mNetComponent;
}
}
I'm using the following gradle declaration for dagger 2:
//Dagger 2
// apt command comes from the android-apt plugin
apt 'com.google.dagger:dagger-compiler:2.7'
compile 'com.google.dagger:dagger:2.7'
provided 'javax.annotation:jsr250-api:1.0'
I could solve the problem by rebuilding the complete project (with errors) and then adding the import of the DaggerNetComponent that was missing before.
Just add #Module to Api class & rebuild the project.
Hope you all doing well.
I was facing the same problem and spent a lot of time over stack overflow. At last I go through this and able to find solution. Briefly, You have to make some changes in your module level Gradle file. Please remove
apply plugin: 'com.neenbedankt.android-apt'
at the top of the file. And replace
apt 'com.google.dagger:dagger-compiler:2.11'
with
annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
After that rebuild your project and you will be able to import your Dagger prefix classes. Hopw it will help you out.

NPE when calling MockitoAnnotations.initMocks() in AndroidTestCase

Trying to use mockito in my AndroidTestCase. I added the dependencies to the build.gradle:
final DEXMAKER_VERSION = '1.2'
dependencies {
// ...
androidTestCompile "com.google.dexmaker:dexmaker:${DEXMAKER_VERSION}"
androidTestCompile "com.google.dexmaker:dexmaker-mockito:${DEXMAKER_VERSION}"
androidTestCompile 'org.mockito:mockito-core:1.10.19'
}
The TestCase with the mockito initialization:
public class UsersListPresenterTest extends AndroidTestCase {
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
public void testInitialize() throws Exception {
}
}
But as soon as I add any attribute to the class, even before adding any annotation the test start to crash:
public class UsersListPresenterTest extends AndroidTestCase {
String mockString;
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
public void testInitialize() throws Exception {
}
}
With the following stacktrace
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com.google.dexmaker.mockito.DexmakerMockMaker.getInvocationHandlerAdapter(DexmakerMockMaker.java:80)
at com.google.dexmaker.mockito.DexmakerMockMaker.getHandler(DexmakerMockMaker.java:75)
at org.mockito.internal.util.MockUtil.isMockitoMock(MockUtil.java:74)
at org.mockito.internal.util.MockUtil.isMock(MockUtil.java:66)
at org.mockito.internal.configuration.injection.scanner.MockScanner.isMockOrSpy(MockScanner.java:86)
at org.mockito.internal.configuration.injection.scanner.MockScanner.preparedMock(MockScanner.java:72)
at org.mockito.internal.configuration.injection.scanner.MockScanner.scan(MockScanner.java:61)
at org.mockito.internal.configuration.injection.scanner.MockScanner.addPreparedMocks(MockScanner.java:47)
at org.mockito.internal.configuration.InjectingAnnotationEngine.injectMocks(InjectingAnnotationEngine.java:96)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processInjectMocks(InjectingAnnotationEngine.java:62)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:56)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
at com.myproject.presentation.UsersListPresenterTest.setUp(UsersListPresenterTest.java:28)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)
What am I doing wrong?
You could try to replace
MockitoAnnotations.initMocks(this);
with this
System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath());
It works for me. See ref here
Its a bug in dexmaker for which I have submitted a fix:
https://github.com/crittercism/dexmaker/pull/24
For me the solution was to use the Method Mockito.mock() for each Mocking Object instead of using MockitoAnnotations.initMocks(this);
So for example:
public class HomePresenterTest {
private Repository repository;
private HomePresenter presenter;
#Before
public void before() {
repository = mock(Respository.class);
presenter = new HomePresenter(repository);
}
//Your tests
}
I've created an issue there https://github.com/mockito/mockito/issues/392
Original answer with hotfix there https://stackoverflow.com/a/36642606/1224247

Categories