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));
}
}
Related
Hi every one I am trying to mock a static method name mapCreditInfo(UCIPin, creditAssessmentResults) which has two parameters UCIPin and creditAssessmentResults. UCIPin is String type and creditAssessmentResults is List
This method is inside a public class ResponseMapper
type as shown below:
private CreditInfo getAccountByUCI(String audiUser, String UCIPin) throws EnterpriseCustomerVerificationException {
List<CreditAssessmentResult> creditAssessmentResults = creditInfoRepository.getUCISummary(UCIPin, audiUser);
return ResponseMapper.mapCreditInfo(UCIPin, creditAssessmentResults);
}
Note: getAccountbyUCI method is called inside another public method
name executeCustomerVerification which is in the class
EnterpriseCustomerVerificationService
ResponseMapper class
public class ResponseMapper {
public static CreditInfo mapCreditInfo(String UCIPin, List<CreditAssessmentResult> creditAssessmentResults) {
CreditInfo creditInfo = new CreditInfo();
creditInfo.setUCIPin(UCIPin);
List<AccountCreditInfo> accountCreditInfos = new ArrayList<AccountCreditInfo>();
for (CreditAssessmentResult creditAssessmentResult : creditAssessmentResults) {
AccountCreditInfo accountCreditInfo = new AccountCreditInfo();
accountCreditInfo.setDelinquenctBalance(creditAssessmentResult.getPastDueAmount());
accountCreditInfo.setNonPayDisconnect(creditAssessmentResult.getNonpayDiscount());
accountCreditInfo.setPreviousAccountNumber(creditAssessmentResult.getAccountNumber());
accountCreditInfo.setUnreturnedEquipmentFlag(creditAssessmentResult.getUnreturnedEquipment());
accountCreditInfos.add(accountCreditInfo);
}
creditInfo.setAccountCreditInfo(accountCreditInfos);
return creditInfo;
}
}
I have Tried like some portion of my test class as shown below :
Test Class
#PrepareForTest( EnterpriseCustomerVerificationService.class)
#RunWith(PowerMockRunner.class)
public class EnterpriseCustomerVerificationServiceTest {
#InjectMocks
private EnterpriseCustomerVerificationService enterpriseCustormerVerificationServiceMock ;
#Test
public void executeCustomerVerificationTest() throws Exception {
List<ErrorResponse> errorResponses = getErrorResponse();
List<String> mso = new ArrayList<String>();
mso.add("a");
mso.add("b");
mso.add("c");
AddressResponse addressResponse = getAddressResponse();
String experianAuthorization = "experianAuthorization";
String UCIPin = "110019";
String auditUser = "ABC";
CreditInfo credit = getCreditInfo();
CreditCheck creditCheck = getcreditCheck();
EnterpriseCustomerVerificationService spy = PowerMockito.spy(new EnterpriseCustomerVerificationService());
PowerMockito.when(spy,PowerMockito.method(EnterpriseCustomerVerificationService.class,"executeCreditCheck",CreditCheck.class)).withArguments(Mockito.any()).thenReturn("#1");
Mockito.when(creditInfoRepository.getUCISummary("110019", "test")).thenReturn(getCreditAssessmentResultList());
PowerMockito.mockStatic(ResponseMapper.class);
Mockito.when(ResponseMapper.mapCreditInfo(UCIPin, getCreditAssessmentResultList())).thenReturn(credit);
CustomerVerification cv = spy
.executeCustomerVerification(getCustomerVerificationRequest1(),
"101");
}
My question is how to mock static mapCreditInfo method using power Mockito ?
Thanks
Like this ...
#RunWith(PowerMockRunner.class)
#PrepareForTest({ResponseMapper.class})
public class ATest {
#Test
public void testMockingStatic() {
PowerMockito.mockStatic(ResponseMapper.class);
// if you want to use specific argument matchers
Mockito.when(ResponseMapper.mapCreditInfo(
uciPin, creditAssessmentResults)
).thenReturn(creditInfo);
// or if you want to match on any arguments passed into your static method ...
Mockito.when(ResponseMapper.mapCreditInfo(
ArgumentMatchers.anyString(),
ArgumentMatchers.anyList())
).thenReturn(creditInfo);
// ...
}
}
Notes:
#PrepareForTest prepares the class with the static methods which you want to mock
PowerMockito.mockStatic mocks all static methods that class
You can use standard Mockito when/then constructs to tell the mocked static methods what to return
The example above uses these dependencies:
org.mockito:mockito-core:2.7.19
org.powermock:powermock-module-junit4:1.7.0
org.powermock:powermock-api-mockito2:1.7.0
Update 1: based on your updated question which shows your test method ...
My example includes: #PrepareForTest({ResponseMapper.class}) your test method is not preparing ResponseMapper instead it is preparing EnterpriseCustomerVerificationService. It's like you are preparing the class which calls the class which has a static method rather than preparing the class which contains the static method.
I would strongly suggest creating a new test case - just temporarily - which looks like the one I have provided and use that to show yourself how to mock a static method and once you are comfortable with that then work that into your EnterpriseCustomerVerificationServiceTest.
Is it possible to change the source code? if so maybe you could try to solve the problem without using any mocking framework at all.
see my comment on How To Java Unit Test a Complex Class
I am trying to write unit test for my below old legacy enum class. The method which I am trying to unit test is - toLocalPookString.
Whenever I am running my unit test code, it is always going inside the if statement in toLocalPookString method since this is always getting resolved to CORP.
public enum DatacenterEnum {
CORP, PHX, SLC, LVS;
private static final DatacenterEnum ourlocation = compareLocation();
private static DatacenterEnum compareLocation() {
// some code here
}
private String toLocalPookString() {
if (this == CORP || !(TestUtils.getEnvironmentName().equalsIgnoreCase("production"))) {
return "/pp/dc/phx";
}
return "/pp/dc/" + name().toLowerCase();
}
public static final String BETA_POOK_STRING = ourlocation.toLocalPookString();
}
Is there any way I can mock this to PHX or SLC or LVS apart from CORP so that in toLocalPookString it should not go inside if statement? I am using jmockit here.
new MockUp<TestUtils>() {
#Mock
public String getEnvironmentName() {
return "production";
}
};
String ss = DatacenterEnum.BETA_POOK_STRING;
System.out.println(ss);
It is pretty simple but somehow I am not able to understand how to do it? Any thoughts?
Well, you could easily mock the enum, as follows:
new MockUp<DatacenterEnum>() {
#Mock DatacenterEnum compareLocation() { return DatacenterEnum.LVS; }
};
However, because the JVM can only perform static initialization once for a given class/enum, the test would only work if the enum hadn't yet been loaded and initialized.
So, a more robust test would be the following.
#Test
public void whenDatacenterIsNotCORPThenLocalPookStringShouldIncludeEnumName() {
new MockUp<TestUtils>() {
#Mock String getEnvironmentName() { return "production"; }
};
DatacenterEnum notCORP = DatacenterEnum.LVS;
String ss = Deencapsulation.invoke(notCORP, "toLocalPookString");
assertTrue(ss.toUpperCase().endsWith(notCORP.name()));
}
This works, but note that writing separate tests for private methods is generally considered bad form. Ideally, tests should call public methods which would indirectly exercise the private ones. In this particular case, however, there is no such public method, so I guess it's acceptable.
I am running some JUnit tests programatically with JUnitCore, and I want to get some data out of the test class once it is finished (so #AfterClass). Here is a pseudocode example of the constraints I am working under:
public class A {
public static String testData;
public static void runTest() {
JUnitCore juc = new JUnitCore();
juc.run(B);
// This is where I would like to access testData for this
// particular run
}
public static void setTestData(String s) {
testData = s;
}
}
public class B {
// Some #Test methods and stuff omitted
#AfterClass
public static void done(String s) {
A.setTestData(someData);
}
}
My problem is that different threads might be calling runTest(), so testData might be wrong. How do I work around this? I'm so lost.
If you really need/want to go with this design, you can make testData a java.lang.ThreadLocal<String>. This will solve the multi-threading issue.
I'm writing unit tests for a block of code that uses introspection; specifically it calls getDeclaredField() on the class I want to mock and tries to get the value of the field. Is there a way to mock this with Mockito?
Mockito operates using the same introspection libraries you're trying to fool by creating a Mock. Even if you could cajole it to work, I'm not sure how easy it would be to understand or maintain.
I'd suggest creating a very small nested class and operating on it normally:
public class YourTest {
private static class SampleClass {
String field1;
int field2;
}
#Test public void introspectionWorks() {
yourSUT.process(new SampleClass());
}
}
Barring that, extract the difficult-to-mock call into a method you can stub easily:
public class YourSUT {
/* ... */
/* package */ Class<?> getFieldType(Object object, String fieldName) {
return object.getClass().getDeclaredField(fieldName).getType();
}
}
public class YourTest {
#Test public void introspectionWorks() {
YourSUT spy = Mockito.spy(yourSUT);
doReturn(String.class).when(spy).getFieldType(myObject, "someStringField");
}
}
I'm using TestNG to run Selenium based tests in Java. I have a bunch of repeated tests. Generally, they do all the same except of test name and one parameter.
I want to automate generation of it. I was thinking about using factory. Is there a way to generate tests with different name? What would be the best approach to this?
As for now I have something like below and I want to create 10 tests like LinkOfInterestIsActiveAfterClick
#Test(dependsOnGroups="loggedin")
public class SmokeTest extends BrowserStartingStoping{
public void LinkOfInterestIsActiveAfterClick(){
String link = "link_of_interest";
browser.click("*",link);
Assert.assertTrue(browser.isLinkActive(link));
}
}
My XML suite is auto-generated from Java code.
Test names are crucial for logging which link is active, and which one is not.
Have your test class implement org.testng.ITest and override getTestName() to return the name you want.
So I connected Factory with DataProvider and used attributes of contexts.
#DataProvider(name = "DP1")
public Object[][] createData() {
Object[][] retObjArr={
{"Link1","link_to_page"},
{"Link2","link_to_page"},
return retObjArr;
}
#Test (dataProvider = "DP1")
public void isActive(String name, String link){
this.context.setAttribute("name", name);
browser.click(link);
Assert.assertTrue(browser.isLinkActive(link));
}
And in the Listener
public class MyListener extends TestListenerAdapter{
#Override
public void onTestSuccess(ITestResult tr){
log("+",tr);
}
//and similar
private void log(String string, ITestResult tr){
List<ITestContext> k = this.getTestContexts();
String testName = tr.getTestClass().getName();
for (ITestContext i: k)
{
if (i.getAttribute("name") != null)
logger.info(testName+"."+i.getAttribute("name"));
}
}
}