Android Studio 3.0 "JUnit version 3.8 or later expected" - java

tried to follow this and this but without any luck.
I am using Android studio 3.0 and junit 4.12. Windows 10.
What I have tried:
move the junit dependency up (tried test compilation and implementation scope)
delete the tests in Run - Edit configurations... - remove all under Android JUnit and Android App
My graddle looks like this:
apply plugin: 'kotlin'
dependencies {
implementation project(':domain')
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompileOnly 'junit:junit:4.12'
testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'
testImplementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testImplementation 'com.nhaarman:mockito-kotlin:1.1.0'
testImplementation 'org.amshove.kluent:kluent:1.14'
implementation 'com.google.api.client:google-api-client-repackaged-com-google-common-base:1.2.3-alpha'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
}
My test looks like this:
package ***.roompanel.data;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.TypeAdapterFactory;
import ***.roompanel.data.RestApi.ApiFieldNamingStrategy;
import ***.roompanel.data.RestApi.ApiGsonBuilder;
import ***.roompanel.data.RestApi.ApiItemTypeAdapterFactory;
import ***.roompanel.data.RestApi.ApiService;
import ***.roompanel.data.RestApi.IApiService;
import ***.roompanel.data.repository.EventRepository;
import ***.roompanel.domain.model.event.Event;
import ***.roompanel.domain.repository.IEventRepository;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertNotNull;
public class EventRepositoryTest {
IEventRepository repo;
#Before
public void setUp() {
TypeAdapterFactory typeAdatperFactory = new ApiItemTypeAdapterFactory(); // system to
FieldNamingStrategy fieldNamingStrategy = new ApiFieldNamingStrategy();
Gson gson = new ApiGsonBuilder(typeAdatperFactory, fieldNamingStrategy).build();
IApiService service = new ApiService(gson);
this.repo = new EventRepository(service);
}
#Test
public void events_void_success() throws Exception {
Date start = new Date(2017,10,01);
Date end = new Date(2017,10,12);
List<Event> events = (List<Event>) repo.load(start, end);
assertNotNull(events);
}
}
UPDATE:
./gradlew test
BUILD SUCCESSFUL in 25s
53 actionable tasks: 30 executed, 23 up-to-date
Stacktrace:
java.lang.RuntimeException: Stub!
at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
at junit.textui.TestRunner.<init>(TestRunner.java:54)
at junit.textui.TestRunner.<init>(TestRunner.java:48)
at junit.textui.TestRunner.<init>(TestRunner.java:41)
at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:224)
at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:207)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

This is not the solution, just a messy workaround (since it took too much time to solve it):
Uninstall and install the android studio 3.0 again. Do not update the
kotlin plugin and the android studio to newer versions.

Related

Gradle not seeing "log" variable definition?

Gradle v7.3.3
I'm trying to use the The Java Platform Plugin, and I have this so far in my platform build.gradle file
artifactId = "my-java-platform"
group = "com.mycompany.platform"
version = "1.0.0"
dependencies {
constraints {
...
api "org.slf4j:slf4j-log4j12:1.7.9"
api "org.projectlombok:lombok:1.16.18"
...
}
}
I did a ./gradlew publishToMavenLocal and see the resulting pom.xml file with those 2 dependencies.
Then in my application's build.gradle file I have
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation platform(group: "com.company.platform", name: "my-java-platform", version: "1.0.0")
annotationProcessor platform(group: "com.company.platform", name: "my-java-platform", version: "1.0.0")
compileOnly group: "org.slf4j", name: "slf4j-log4j12"
compileOnly group: "org.projectlombok", name: "lombok"
...
}
One of my applications source code has
package com.mycompany.common
import java.util.TimeZone;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import lombok.extern.slf4j.Slf4j;
#Slf4j
public class ObjectMapperConfiguration {
private static ObjectMapper objectMapper;
/**
* Static only
*/
private ObjectMapperConfiguration() {}
/**
* Work with Spring to configure the ObjectMapper
*/
public static ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
objectMapper = builder.createXmlMapper(false).build();
configureObjectMapper(objectMapper);
log.info("The ObjectMapperConfiguration has run");
return objectMapper;
}
...
}
But I get
$ ./gradlew clean build
> Task :compileJava FAILED
/Users/.../src/main/java/com/company/common/ObjectMapperConfiguration.java:39: error: cannot find symbol
log.info("The ObjectMapperConfiguration has run");
^
symbol: variable log
location: class com.company.common.ObjectMapperConfiguration
I understand that the log variable is defined in the #Slf4j annotation? If so why am I getting the error? Thanks!
The Lombok magic is implemented via an annotation processor.
See here for the recommended Lombok Gradle config
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.22'
annotationProcessor 'org.projectlombok:lombok:1.18.22'
testCompileOnly 'org.projectlombok:lombok:1.18.22'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.22'
}
The application's build.gradle file, the one that uses the platform, should look like this
dependencies {
implementation platform(group: "com.mycompany.platform", name: "my-java-platform", version: "1.0.0")
annotationProcessor platform(group: "com.company.platform", name: "my-java-platform", version: "1.0.0")
annotationProcessor group: "org.projectlombok", name: "lombok"
...
}

How to fix this error: java.lang.NoSuchMethodError: 'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'

So I am getting this error in my Spring boot Gradle project:
'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'
java.lang.NoSuchMethodError: 'java.lang.AutoCloseable org.mockito.MockitoAnnotations.openMocks(java.lang.Object)'
And I cannot seem to fix it. I have searched for the answer but the only one I get is removing mockito-all from your dependencies, but I do not have that in my gradle.build file in the first place.
My build.gradle file:
plugins {
id 'org.springframework.boot' version '2.4.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id "org.sonarqube" version "3.0"
id 'jacoco'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
implementation('io.jsonwebtoken:jjwt:0.2')
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compile 'junit:junit:4.12'
implementation 'org.modelmapper:modelmapper:2.4.1'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.eclipse.jgit:org.eclipse.jgit:5.4.2.201908231537-r'
/**
* JUnit jupiter with mockito.
*/
testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.19.0'
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
testCompile group: 'org.springframework.security', name: 'spring-security-test', version: '5.1.6.RELEASE'
}
sonarqube{
properties{
property 'sonarjava.source', '1.8'
property 'sonar.java.coveragePlugin', 'jacoco'
property 'sonar.jacoco.reportPaths', 'build/reports/jacoco/test/jacocoTestReport.xml'
}
}
test {
useJUnitPlatform()
}
I can't seem to find a solution so I came to here, where some code god maybe can help me fixing my problem.
The file where I get this error on is a test class:
The test class:
package com.example.demo.Service;
import com.example.demo.DTO.PartyLeaderDto;
import com.example.demo.Model.PartyLeader;
import com.example.demo.Repository.PartyLeaderRepository;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.verify;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.modelmapper.ModelMapper;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.argThat;
#SpringBootTest
#AutoConfigureMockMvc
public class PartyLeaderServiceMockTest {
#Rule
public MockitoRule initRule = MockitoJUnit.rule();
#Mock
private PartyLeaderRepository partyLeaderRepository;
#Mock
private ModelMapper modelMapper;
#InjectMocks
private PartyLeaderService partyLeaderService; // this is like calling new PartyLeaderService(partyLeaderRepository, modelMapper);
#Test
void whenSavePartyLeader_thenCorrectPartyLeaderSaved() {
// given
var input = PartyLeaderDto.builder()
.name("Josse")
.apperance("Link of image")
.build();
// when
partyLeaderService.savePartyLeader(input);
// then
verify(partyLeaderRepository).save(argThat(entity ->
entity.getName().equals("Josse")
&& entity.getApperance().equals("Link of image")));
}
#Test
void whenGetPartyLeader_ShouldReturnCorrectLeaderData() {
// given
var partyLeaderEntity = PartyLeader.builder()
.name("Josse")
.apperance("Link of image")
.build();
var partyLeaderDto = PartyLeaderDto.builder()
.name("Josse")
.apperance("Link of image")
.build();
when(partyLeaderRepository.findById(3)).thenReturn(Optional.of(partyLeaderEntity));
when(modelMapper.map(partyLeaderEntity, PartyLeaderDto.class)).thenReturn(partyLeaderDto);
// when
var result = partyLeaderService.getPartyLeader(3);
// then
Assert.assertEquals(result, partyLeaderDto);
}
}
I get the same error on both of my tests.
Can anyone help me? Thanks in advance!
Issue was due to the jar conflicts
We need to exclude
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
</exclusion>
</exclusions>
</dependency>
And include
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.2</version>
</dependency>
After facing the same issue. Please look log trace.
java.lang.NoSuchMethodError: org.mockito.MockitoAnnotations.openMocks(Ljava/lang/Object;)Ljava/lang/AutoCloseable;
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.initMocks(MockitoTestExecutionListener.java:83)
Finally got a solution:
In Mockito version 2 there is a MockitoAnnotations.initMock() method, which is deprecated and replaced with MockitoAnnotations.openMocks() in Mockito JUnit 5 version 3. The MockitoAnnotations.openMocks() method returns an instance of AutoClosable which can be used to close the resource after the test.
Manual Initialization
Before doing anything else, we have to add the Mockito dependency.
dependencies {
testImplementation('org.mockito:mockito-core:3.7.7')
}
The MockitoAnnotations.openMocks(this) call tells Mockito to scan this test class instance for any fields annotated with the #Mock annotation and initialize those fields as mocks.
Pros:
Easy to create mocks
Very readable
Cons:
Does not validate framework usage or detect incorrect stubbing
Automatic Mock Injection
We can also tell Mockito to inject mocks automatically to a field annotated with #InjectMocks.
When MockitoAnnotations.openMocks() is called, Mockito will:
Create mocks for fields annotated with the #Mock annotation
Create an instance of the field annotated with #InjectMocks and try to inject the mocks into it
Using #InjectMocks is the same as we did when instantiating an instance manually, but now automatic.
public class MockitoInjectMocksTests {
#Mock
private OrderRepository orderRepository;
private AutoCloseable closeable;
#InjectMocks
private OrderService orderService;
#BeforeEach
void initService() {
closeable = MockitoAnnotations.openMocks(this);
}
#AfterEach
void closeService() throws Exception {
closeable.close();
}
#Test
void createOrderSetsTheCreationDate() {
Order order = new Order();
when(orderRepository.save(any(Order.class))).then(returnsFirstArg());
Order savedOrder = orderService.create(order);
assertNotNull(savedOrder.getCreationDate());
}
}
Mockito will first try to inject mocks by constructor injection, followed by setter injection, or field injection.
Pros:
Easy to inject mocks
Cons:
Doesn’t enforce usage of constructor injection
For me, none of the workarounds mentioned here worked.
Updating mockito-core from 3.3.3 to 3.4.3 fixed the problem.
I think it is caused by the fact that the MockitoAnnotations.initMock() method is deprecated and has been replaced by MockitoAnnotations.openMocks() in Mockito JUnit 5 version 3.
On the other hand, it may be worthy to check the local Maven Repository and delete unnecessary jars that may cause conflict. But when applying this step, beware not to manually delete installed ones (or do a backup before the operation).
I've faced the same problem I've fixed it by using
Mockito.mock() method instead of #Mock.
I use spring-boot-starter-test v2.4.8 and mockito-core v2.21.0
In my case the error occurred because in initMocks method from MockitoTestExecutinListener class looks like this:
private void initMocks(TestContext testContext) {
if (hasMockitoAnnotations(testContext)) {
testContext.setAttribute(MOCKS_ATTRIBUTE_NAME, MockitoAnnotations.openMocks(testContext.getTestInstance()));
}
}
but in my case MockitoAnnotations have only initMocks() method, so the error.
In this case we need to make sure that hasMockitoAnnotations(testContext) is false.
In order to use #Mock I need to enable Mockito annotations, but I do not want this, therefore I used Mockito.mock().

How to run PowerMock v1.74 with java.net.InetAddress static method

I have been reading a lot about PowerMockito to mock static methods. So I have been trying to use v1 (not v2), although I don't really care which version of PowerMockito or testNG I use. I figure I missed some critical detail here in the configuration, but I am at a loss.
Using Oracle Java 1.8
subprojects.gradle:
testCompile group: 'org.testng', name: 'testng', version: '6.14.3'
testCompile group: 'org.powermock', name: 'powermock-module-testng', version: '1.7.4'
testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.7.4'
I checked my versioning of modules here
Test class
import org.mockito.*;
import org.mockito.invocation.*;
import org.mockito.stubbing.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.testng.*;
import org.testng.*;
import org.testng.annotations.*;
import java.io.*;
import java.net.*;
import static org.powermock.api.mockito.PowerMockito.*;
#PrepareForTest({java.net.InetAddress.class})
public class testClass extends PowerMockTestCase {
#Test
public void exampleTest()
throws IOException, URISyntaxException, MyCustomException {
mockStatic(InetAddress.class);
// I use these three functions, so I think I have to mock them all?
when(InetAddress.getByName(Mockito.anyString()))
.thenReturn(InetAddresses.forString("111.0.0.111"));
when(InetAddress.getByAddress(Mockito.anyObject()))
.thenCallRealMethod();
when(InetAddress.getLocalHost()).thenCallRealMethod();
MyNewClass mnc = new MyNewClass();
mnc.someCodeUsingInetAddress();
}
This compiles and runs, but does not change the behavior of the function InetAddress.getByName() when called from someCodeUsingInetAddress().
Now I read here that I need to label the class with
#RunWith(PowerMockRunner.class). But IntelliJ won't let me import the PowerMockRunner.class from any of the possible sources, of which it is aware. Which also makes me wonder which one I should be trying to use.
org.testng.PowerMockRunner
org.testng.annotations.PowerMockRunner
org.powermock.modules.testng.PowerMockRunner
the list goes on...

Setting up Roboelectric testing for android

I am trying to add some Roboelectric unit tests to my app.
Using Roboelectric 3.0 i want to be able to test my activity PinActivity and the fragment that is in it.
import android.support.v7.app.AppCompatActivity;
import android.app.Fragment;
PinActivity extends AppCompatActivity {
gradle file contains:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.0"
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}
PinActivityTest contains: (Edited to add #Config did not fix)
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.*;
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class, sdk = 21)
public class PinActivityTest {
#Test
public void onCreate_shouldInflateLayout() throws Exception {
PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get();
assertNotNull(activity);
}
Currently getting:
WARNING: No manifest file found at .\AndroidManifest.xml.Falling back to the Android OS resources only. To remove this warning, annotate your test class with #Config(manifest=Config.NONE). and java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
Why can't it find my AndroidManifest?
Anyone know how i can fix this or more Roboelectric tutorials with similar examples?
As log says, you forgot about #Config annotation, so it could not find your AndroidManifest file:
Try this:
#RunWith(RobolectricGradleTestRunner.class)
#Config(constants = BuildConfig.class, sdk = 21) public class PinActivityTest {
#Test
public void onCreate_shouldInflateLayout() throws Exception {
PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get();
assertNotNull(activity);
}
As Roboelectric not support already API23, I set up test sdk as API 21.
EDIT: Change also:
PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get()
to
PinActivity activity = Robolectric.setupActivity(PinActivity.class);
NOTE: My Robolectric dependencies looks now:
testCompile("org.robolectric:robolectric:3.0") {
exclude module: 'classworlds'
exclude module: 'commons-logging'
exclude module: 'httpclient'
exclude module: 'maven-artifact'
exclude module: 'maven-artifact-manager'
exclude module: 'maven-error-diagnostics'
exclude module: 'maven-model'
exclude module: 'maven-project'
exclude module: 'maven-settings'
exclude module: 'plexus-container-default'
exclude module: 'plexus-interpolation'
exclude module: 'plexus-utils'
exclude module: 'wagon-file'
exclude module: 'wagon-http-lightweight'
exclude module: 'wagon-provider-api'
}
If you have any question, please free to ask.
Hope it help

AndroidStudio Robolectric Unit Tests - Invaild default

I want to use Unit Testsfor my Android Application. First, I've tried the Unit-Tests with Robolectric with a template Project "deckard-gradle-master". As it worked fine, I wanted to integrate this testing in my existing Android Application.
I have added the libraries hamcrest-core-1.3.jar, junit-4.12.jar, robolectric-2.4.jar and robolectric-gradle-plugin-1.0.1.jar.
When i try to start my TestClass in this Project, I always get the following Exception:
Exception in thread "main" java.lang.annotation.AnnotationFormatError: Invalid default: public abstract java.lang.Class org.robolectric.annotation.Config.application()
at java.lang.reflect.Method.getDefaultValue(Method.java:611)
at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:128)
at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:85)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:266)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getAnnotation(Class.java:3415)
at com.intellij.junit4.JUnit4TestRunnerUtil.buildRequest(JUnit4TestRunnerUtil.java:199)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:39)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
I really don't know what to do anymore, but i think something is missing. Unfortunately i don't know what.
These are my gradle-files:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
and
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.example.bieren.myapplication"
minSdkVersion 19
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:21.0.3'
compile files('libs/junit-4.12.jar')
compile files('libs/robolectric-2.4.jar')
compile files('libs/robolectric-annotations-2.4.jar')
compile files('libs/hamcrest-core-1.3.jar')
compile files('libs/android.jar')
compile files('libs/android-libcore-4.3_r2.robolectric-0.jar')
compile files('libs/robolectric-2.4-jar-with-dependencies.jar')
compile files('libs/android-support-v4.jar')
compile files('libs/maps.jar')
androidTestCompile 'org.hamcrest:hamcrest-integration:1.1'
androidTestCompile 'org.hamcrest:hamcrest-core:1.1'
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
androidTestCompile('junit:junit:4.+') {
exclude module: 'hamcrest-core'
}
androidTestCompile('org.robolectric:robolectric:2.3') {
exclude module: 'classworlds'
exclude module: 'commons-logging'
exclude module: 'httpclient'
exclude module: 'maven-artifact'
exclude module: 'maven-artifact-manager'
exclude module: 'maven-error-diagnostics'
exclude module: 'maven-model'
exclude module: 'maven-project'
exclude module: 'maven-settings'
exclude module: 'plexus-container-default'
exclude module: 'plexus-interpolation'
exclude module: 'plexus-utils'
exclude module: 'support-v4'
exclude module: 'wagon-file'
exclude module: 'wagon-http-lightweight'
exclude module: 'wagon-provider-api'
}
compile files('libs/robolectric-gradle-plugin-1.0.1.jar')
}
This is my Testclass:
package com.example.bieren.testapplication.test;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
#RunWith(RobolectricTestRunner.class)
#Config(manifest = "src/main/AndroidManifest.xml", emulateSdk = 18)
public class MainActivityTest {
private MainActivity activity;
#Test
public void testIcon() throws Exception {
String play_icon = new MainActivity().getResources().getString(R.string.icon_play);
assertThat(play_icon, equalTo(""));
}
#Before
public void setup(){
this.activity = Robolectric.buildActivity(MainActivity.class).create().get();
}
#Test
public void buttonClickShouldSetText() throws Exception
{
Button button = (Button) activity.findViewById(R.id.button);
TextView textView = (TextView) activity.findViewById(R.id.nachricht);
textView.setText("Hans Hans");
button.performClick();
assertEquals(textView.getText(),"Hans Hans");
}
}
I would really be more than thankful if someone could tell me whats the problem and what's missing.
Timon
Deleting the .gradle folder works for me every time!
If you do not find the .gradle folder, this might be hidden. In that case, go to your project directory and run the following command to remove the .gradle folder.
rm -rf .gradle/
Changing the #Config to
#Config(manifest = "app/src/main/AndroidManifest.xml", emulateSdk = 18, reportSdk = 18)
solved the problem for me.
If you use the new testing environment, configuring Robolectric is more seamless. Look at this link in order to set up your project with the new testing environment.
Just as a heads up, you will need to upgrade Android Studio to 1.1 RC1 or greater for this to work.
This approach avoids having to use any kind of plugin for Robolectric.

Categories

Resources