Unit testing: Entry name 'res/layout/test_toolbar.xml' collided - java

I've tried to do some unit test example that included in an Android Studio project like ExampleInstrumentedTest and ExampleUnitTest, so the result is :
Entry name 'res/layout/test_toolbar.xml' collided
I've searched everywhere on google but there's not answers to this specific problem, so any help will be grateful
here's the source of the basic unit test example :
ExampleUnitTest
* Example local unit test, which will execute on the development machine (host).
*
* #see Testing documentation
*/
public class ExampleUnitTest {
#Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}}
ExampleInstrumentedTest
* Instrumented test, which will execute on an Android device.
*
* #see Testing documentation
*/
#RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
#Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getContext();
assertEquals("com.example.abder.emarque", appContext.getPackageName());
}}

I just did the following and It solved my problem.
Invalidate caches and Restart (File -> Invalidate Caches / Restart)
Clean Project (Build -> Clean Project)

This happens due to same xml may be included in third party SDKs.
Solution: exclude 'res/layout/test_toolbar.xml' in packagingOptions of app's build.gradle file.
packagingOptions { exclude 'res/layout/test_toolbar.xml' }

Related

Gradle Settings plugin extension

I want to create a settings plugin (not project plugin) to simplify some stuff, but I cannot get the configuration clause to work.
This is my plugin (Java code)
public class SettingsPlugin implements Plugin<Settings> {
#Override
public void apply(Settings target) {
target.getExtensions()
.create("modules", IncludeModulesExtension.class, target);
System.err.println("Applied settings plugin");
}
}
public class IncludeModulesExtension {
private final Settings _settings;
public IncludeModulesExtension(Settings settings) {
_settings = settings;
}
public void include(String path) {
}
}
My problem is, that gradle is not picking up the "modules" dynamic function in my settings.gradle.kts:
pluginManagement {
...
}
plugins {
id("com.ieffects.gradle-tools.settings-server") version ("7.0.23-SNAPSHOT")
}
modules {
}
I omitted the pluginManagement, the plugin is found and applied, however the "modules" is not picked up. What is it I'm doing wrong?
Starting Gradle Daemon...
Gradle Daemon started in 2 s 396 ms
Applied settings plugin
e: /Volumes/Development/Git/server-framework-galcon/settings.gradle.kts:22:1: Unresolved reference: modules
FAILURE: Build failed with an exception.
* Where:
Settings file '/Volumes/Development/Git/server-framework-galcon/settings.gradle.kts' line: 22
* What went wrong:
Script compilation error:
Line 22: modules {
^ Unresolved reference: modules
1 error
I faced the same issue when implementing a similar plugin, and although I didn't find out why, I did manage to work around it:
// SettingsExtensions.kt
import org.gradle.api.Action
import org.gradle.api.initialization.Settings
import org.gradle.api.plugins.ExtensionAware
/* WORKAROUND: for some reason a type-safe accessor is not generated for the extension,
* even though it is present in the extension container where the plugin is applied.
* This seems to work fine, and the extension methods are only available when the plugin
* is actually applied. */
/**
* Retrieves the [modules][IncludeModulesExtension]
* extension.
*/
val Settings.modules: IncludeModulesExtension
get() =
(this as ExtensionAware).extensions.getByName("modules") as IncludeModulesExtension
/**
* Configures the [modules][IncludeModulesExtension] extension.
*/
fun Settings.modules(configure: Action<IncludeModulesExtension>): Unit =
(this as ExtensionAware).extensions.configure("modules",
configure)
As the comment explains, it behaves exactly the same as a generated type-safe accessor (same syntax and the extension is only available when the plugin is actually applied).
I didn't test if it works for the Groovy DSL, but since the extension methods are syntactically identical to the generated accessors, I assume it does.
Alternatively you can do without if instead of the modules DSL you do this in the settings script where the plugin is applied:
configure<IncludeModulesExtension> {
...
}
This also works because even though the type-safe accessor is not generated, the extension is properly initialized and added to the extensions container. But the DSL is obviously nicer.

Why Unit Tests Assertion fail on Gradle 5.1, but passes on 1.12, both use same Java version 1.8?

I have a multi-module project which is using
Java 1.8
JUnit 4.12
Gradle
When compiling a single module, its unit tests are failing on asserting null with Gradle 5.1, but same tests pass on Gradle 1.12 and module compiles successfully. Not changing anything except what is deprecated in 5.1. I can't understand why same framework fails on a recent Gradle version.
One test fails on JUunit Assert.assertNotNull(), which is checking for a string is null or not.
A second test fails on JUnit Assert.assertTrue().
build.gradle is same in both except configuration name changes and I have confirmed all dependencies are downloaded and compiling.
Can't share build script, but if you don't understand something I'll try to make a pseudo script.
I thought assertion errors were more related to language version than tools?
public class Test {
private String property;
#Before
public void setUp() {
property = Singleton.getInstance().getProperty();
}
// test failure 1
#Test
public void shouldAbleToGetProperty() {
assertNotNull(property);
}
// test failure 2
#Test
public void shouldReturnTrueIfPropertyIsTrue() {
Assert.assertTrue(Singleton.getInstance().isTrue());
}
}
Singleton class is a normal singleton which reads property files in resources folder.
NOT ACTUAL CODE
class Singleton {
private Map<String, Properties> properties;
public static Singleton getInstance() {
// return singleton as its meant to be ...
// read property file from project and hold it in map.
}
}

I faced two error when I run my retrofit test with robolectric befor the test starts

I have written this test in test pakage, for test of a retrofit class, but even before test stars,in addition to unknownable "constants" in #Config, this error is shown:
#Config(constants = BuildConfig.class, sdk =21, manifest="app/manifests/AndroidManifest.xml")
#RunWith(RobolectricTestRunner.class)
public class MultiFactorAPITest {
private MainActivity mainActivity;
#Mock
private MultiFactorAPI mockMultiFactorAPI;
#Captor
private ArgumentCaptor<Callback<List<ValidatePhoneUserResponse>>> callbackArgumentCaptor;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
mainActivity = controller.get();
// Then we need to swap the retrofit api impl. with a mock one
// We store our Retrofit api impl as a static singleton in class RestClient, hence:
RestClient.setApi(mockMultiFactorAPI);
controller.create();
}
The error is:
Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor. Please add them to the annotationProcessor configuration.
- auto-service-1.0-rc4.jar (com.google.auto.service:auto-service:1.0-rc4)
Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior. Note that this option is deprecated and will be removed in the future.
See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.
I've added these lines to gargle to:
dependencies {
implementation 'org.robolectric:robolectric:4.3'
implementation "org.mockito:mockito-core:1.10.19"
implementation 'org.hamcrest:hamcrest-library:1.1'
}
in gradle.Madule:
android{
testOptions {
unitTests {
includeAndroidResources = true
}
} }
in gradle.app:
dependencies{
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
}
in gradle.propertice:
android.enableUnitTestBinaryResources=true
android.enableAapt2=false
my problem solved by putting this code in my app.gradle :
dependencies{
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.okhttp3:mockwebserver:3.6.0'
}
and
1) find the location of of your .gradle folder, in Android Studio goto File->Settings and type "gradle" in the search box. You will be able to pick up the correct path there
2)Remove the .gradle directory (mine's location was C:\Users\UserName.gradle), and restart android studio. It will automatically create a new one.
from Android studio: build project error - Failed to complete Gradle execution

Kotlin class runs as junit tests even when it is in androidTest package - for Java class it runs normally

I've run into very strange error.
When i try to run test that are in my Kotlin class in androidTest package they are running as test junit mehthods and this error appears:
Process finished with exit code 1
Class not found: "com.someampp.shoppinglistapp.SomeClassTest"Empty test suite.
You can try it for yourself. I am using Android Studio 3.0.1
When i am creating class like this in Java:
#RunWith(AndroidJUnit4.class)
public class SomeTestClass{
#Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.myapp.shoppinglistapp", appContext.getPackageName());
}
}
Everything works fine.
But when i convert the Java file to Kotlin:
#RunWith(AndroidJUnit4::class)
class SomeTestClass{
#Test
#Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.myapp.shoppinglistapp", appContext.packageName)
}
}
It gives me this error.
Whats wrong?
You need to open Run/Debug configurations and create one for Android Instrumented Tests instead of Android JUnit.

How to debug Solr plugin?

I have written a search component to be used with SOLR. I want to debug it. I tried debugging the SOLR itself using remote debugging feature of eclipse but it doesn't work for plugin and shows source not found.
Then I tried including my plugin project as source project but that did not work either. The debugger doesn't stops at breakpoints for plugin.
Any help in this regard shall be greatly appreciated!
You can write a Junit test in your eclipse project using an embedded solr. This makes debugging easier. All you need to do, is to create the config files for the solr-core (solrconfig.xml, schema.xml, etc.; you could probably copy the solr core dir from your solr installation) in your test resources directory and point the CoreContainer to that directory. This core container can be used to get the configured solr core and your searcher.
JUnit and Solr-core are the dependencies needed.
Below is an example of the test-code:
/**
* This is a starting point for testing the component with embedded solr!
*/
public class SearchComponentTest
{
private static CoreContainer container;
private static SolrCore core;
private static final Logger logger = LoggerFactory.getLogger(DataImportRequestHandlerTest.class.getName());
/*
* PREPARE AND TEAR DOWN FOR TESTS
*/
#BeforeClass
public static void prepareClass() throws Exception
{
// create the coreContainer from conf dir in test resources
container = new CoreContainer(
DataImportRequestHandlerTest.class.getResource("/solrDir").getPath().substring(1));
container.load();
core = container.getCore("CORENAME");
logger.info("Solr core loaded!");
}
#AfterClass
public static void cleanUpClass()
{
core.close();
container.shutdown();
logger.info("Solr core shut down!");
}
/* TESTS TO RUN */
/**
* Test the search component here or just trigger it to debug
*/
#Test
public void testSearchComponent()
{
/* PREPARE */
SearchComponent mySearchComp = core.getSearchComponent("componentNameFromSolrConf");
/* RUN */
// do something with your search component
/* CHECK */
// check results with asserts :)
}
}

Categories

Resources