I have made a sample application in android and included the aar file in it and i have peform unit testing for the application whether it is possible to carry out unit testing for the sample application?
Consider the below Sample Class for UnitTesting
public class SampleUnitTestClass {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
After creating the class use the shortcut,Ctrl+Shift+T to create a new Test class corresponding to your sample Class.
Click on Create new Test
Select the methods that you want in your Unit test class and click ok(You could also change the Class name, destination package, Testing Library if needed)
Select destination directory and click OK
A Unit test class will be created
public class SampleUnitTestClassTest {
#Test
public void add() throws Exception {
}
#Test
public void subtract() throws Exception {
}
}
Write your testing logic here and asset your answer.For eg:
public class SampleUnitTestClassTest {
#Test
public void add() throws Exception {
SampleUnitTestClass testClass = new SampleUnitTestClass();
int answer = testClass.add(2,7);
assertEquals("Addition of 2 positive integers",9,answer);
}
#Test
public void subtract() throws Exception {
SampleUnitTestClass testClass = new SampleUnitTestClass();
int answer = testClass.subtract(2,7);
assertEquals("Subtraction of 2 positive integers",-5,answer);
}
}
Add more methods to include negative , null values etc and assert the answer.
For Unit Testing you can use Mockito and if u require some Android resources as well you can read about Robolectric.
Related
I am using Flink v.1.4.0.
I have implemented a module, as part of a package I am developing, whose role is to deduplicate a stream. The module is quite simple:
public class RemoveDuplicateFilter<T> extends RichFlatMapFunction<T, T> {
static final ValueStateDescriptor<Boolean> SEEN_DESCRIPTOR = new ValueStateDescriptor<>("seen", Boolean.class);
private ValueState<Boolean> seen;
#Override
public void open(Configuration configuration) {
RuntimeContext runtimeContext = this.getRuntimeContext();
seen = runtimeContext.getState(SEEN_DESCRIPTOR);
}
#Override
public void flatMap(T value, Collector<T> out) throws Exception {
Boolean hasBeenSeen = seen.value();
if(hasBeenSeen == null || !hasBeenSeen) {
out.collect(value);
seen.update(true);
}
}
The question is: how do I test this code without having to instantiate an actual Flink ValueState? i.e. using Mockito?
I have tried a number of things but, essentially, when it comes down to calling:
RuntimeContext runtimeContext = Mockito.mock(RuntimeContext.class);
...
when(runtimeContext.getState(SEEN_DESCRIPTOR)).thenReturn(seen);
The call always fails. I have tried replacing the SEEN_DESCRIPTOR with Matchers.any() but still no luck.
Any suggestions?
You can use flinkspector to do unit-testing of functions.
How can I mock a class which is used in another class using only powerMock or EasyMock,I can only use this two frameworks ,I know we can use Mockito but as our codebase contains only easymock and powermock library I have to stick the two frameworks only .
I have below code ( I am using powerMock )
public class ClassUnderTest {
public void getRecord() {
System.out.println("1: In getRecord \n");
System.out.println("\n 3:"+SecondClass.getVoidCall());
System.out.println("\n 4: In getRecord over \n");
}
}
I want to mock the method SecondClass.getVoidCall() .
public class ArpitSecondClass {
public static int getVoidCall() {
System.out.println("\n 2: In ArpitSecondClass getVoidCall for kv testing\n");
return 10;
}
}
My Unit Test code is
#RunWith(PowerMockRunner.class)
#PrepareForTest(TestArpit.class)
public class UniteTestClass {
#Test
public void testMock() throws Exception {
SecondClass class2 = createMock(SecondClass.class);
expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
expectLastCall().anyTimes();
ClassUnderTest a=new ClassUnderTest ();
a.getRecord();
replayAll();
PowerMock.verify();
}
}
Basically I want the output as below
1: In getRecord
2: In ArpitSecondClass getVoidCall for kv testing
3:20 (Note:This should be overriden by the value I supplied in UnitTest)
4: In getRecord over
But the output which I am getting with the Unitest code is
2: In ArpitSecondClass getVoidCall for kv testing
The code flow doesnt go beyond expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
And the remaining statments in getRecord are not printed as it's never called at all.
Am I missing something here ?
The SecondClass#getVoidCall() method (public static int getVoidCall() {...}) is a static method and, as such, the mocking is a little different.
Replace the first two lines:
#Test
public void testMock() throws Exception {
SecondClass class2 = createMock(SecondClass.class);
expect(class2.getVoidCall()).andReturn(20).atLeastOnce();
With the lines below (and prepare the class):
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.mockStatic;
...
#RunWith(PowerMockRunner.class)
#PrepareForTest({TestArpit.class, SecondClass.class}) // added SecondClass.class here
public class UniteTestClass {
#Test
public void testMock() throws Exception {
mockStatic(SecondClass.class); // changed this line
expect(SecondClass.getVoidCall()).andReturn(20).atLeastOnce(); // changed this line
Suppose I have the following class :
public class Math {
public int mult(int a, int b) {
return 4;
}
public int mul (int a, int b) {
return mult(a,b);
}
}
And the following test class :
public class TestMockito {
Math testMath;
#Before
public void create () {
testMath = *mock*(Math.class);
when(testMath.mult(1,2).thenReturn(2);
}
#Test
public void test() {
System.out.println(testMath.mul(1,2));
}
}
Why does mul(1,2) called in test() not use when(testMath.mult(1,2).thenReturn(2); ?
Is there any other way to mock a method being used inside another method that is being tested ?
Cheers
You usually do not mock the code under test (unless it is an abstract class).
You usually mock other classes (the dependencies) your CUT communicates with.
The reason why your test does not work (as you expect) is that the mock is not an object of the real class (which is the reason why we mock it BTW....). It has been derived by the mocking framework not to behave like the original code but like it has been configured for the test.
If you really want the real methods being called in the mock (which is not what you want most of the time) you need to tell mockito that when creating the mock:
mock(ClassToBeMocked.class,Mockito.CALL_REAL_METHODS);
I receive a string from a server in the main activity .I have to write a test case for that (whether the string is received in the correct format) How do I write a test case for methods in android ? I am completely new to Testing and any resources are greatly helpful
As you don't want to test the Activity but rather the business logic, you could factor out the receiving of the String to an own class and test this class instead in an isolated way where you don't have any Android specifics around. For example, you could write a POJO class ServerValidator which receives a String and returns a boolean value and you use this validator in your activity and can test it without needing any Android surroundings.
public class ServerValidator {
public static boolean validate(String input) {
return ...; // Insert validation logic
}
}
public class ServerValidatorTest {
#Test
public void testValidateFailure() {
final String faultyString = ...;
Assert.assertFalse(ServerValidator.validate(faultyString));
}
#Test
public void testValidateSuccessful() {
final String correctString = ...;
Assert.assertTrue(ServerValidator.validate(correctString));
}
}
I want to back up my application's database before replacing it with the test fixture. I'm forced to use Junit3 because of Android limitations, and I want to implement the equivalent behavior of #BeforeClass an #AfterClass.
UPDATE: There is now a tool (Junit4Android) to get support for
Junit4 on Android. It's a bit of a kludge but should work.
To achieve the #BeforeClass equivalent, I had been using a static variable and initializing it during the first run like this, but I need to be able to restore the database after running all the tests. I can't think of a way of detecting when the last test has run (since I believe there is no guarantee on the order of test execution.)
public class MyTest extends ActivityInstrumentationTestCase2<MainActivity> {
private static boolean firstRun = true;
#Override
protected void setUp() {
if(firstRun) {
firstRun = false;
setUpDatabaseFixture();
}
}
...
}
From the junit website:
Wrapped the setUp and tearDown method in the suite.This is for the
case if you want to run a single YourTestClass testcase.
public static Test suite() {
return new TestSetup(new TestSuite(YourTestClass.class)) {
protected void setUp() throws Exception {
System.out.println(" Global setUp ");
}
protected void tearDown() throws Exception {
System.out.println(" Global tearDown ");
}
};
}
If you would like to run only one setUp and tearDown for all the
testcase, make a suite and add testClass to it and pass the suite
object in TestSetup constructor.But I think there is not much usage
for this,and in a way it is violating JUnit philosophy.
Recently, I was looking for a similar solution too. Fortunately, in my case after the JVM exits after the last test is run. So I was able to achieve this by adding a JVM shutdown hook.
// Restore database after running all tests
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
restoreDatabase();
}
});
hope this helps.
I would suggest avoiding these kind of dependencies where you need to know the order in which tests are run. If all you need is to restore a real database that was replaced by setUpDatabaseFixture() probably you solution comes from the use of a RenamingDelegatingContext. Anyway, if you can't avoid knowing when the last test was run, you can use something like this:
...
private static final int NUMBER_OF_TESTS = 5; // count your tests here
private static int sTestsRun = 0;
...
protected void tearDown() throws Exception {
super.tearDown();
sTestsRun += countTestCases();
if ( sTestsRun >= NUMBER_OF_TESTS ) {
android.util.Log.d("tearDow", "*** Last test run ***");
}
}
Isn't this (dealing elegantly with data, so you don't have to worry about restoring it) what testing with mock objects are for? Android supports mocking.
I ask as a question, since I've never mocked Android.
In my experiences, and from this blog post, when the Android tests are made into a suite and run by the InstrumentationTestRunner - ActivityInstrumentationTestCase2 is an extension of ActivityTestCase which is an extendsion of InstrumentationTestCase - they are ordered alphabetically using android.test.suitebuilder.TestGrouping.SORT_BY_FULLY_QUALIFIED_NAME, so you can just restore you DB with a method that is the lowes in the alphabet out of your test names, like:
// underscore is low in the alphabet
public void test___________Restore() {
...
}
Note:
You have to pay attention to inherited tests, since they will not run in this order. The solution is to override all inherited test and simply call super() from the override. This will once again have everything execute alphabetically.
Example:
// Reusable class w only one time setup and finish.
// Abstract so it is not run by itself.
public abstract class Parent extends InstrumentationTestCase {
#LargeTest
public void test_001_Setup() { ... }
#LargeTest
public void test_____Finish() { ... }
}
/*-----------------------------------------------------------------------------*/
// These will run in order shown due to naming.
// Inherited tests would not run in order shown w/o the use of overrides & supers
public class Child extends Parent {
#LargeTest
public void test_001_Setup() { super.test_001_Setup(); }
#SmallTest
public void test_002_MainViewIsVisible() { ... }
...
#LargeTest
public void test_____Finish() { super.test_____Finish(); }
}