I have a test class in Android test package. There is a class that I've create an object in it. But other method of this test class can not use this object and can not recognize the result of that method. Why and what should I do? I used static too but can't...
#RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private static int newRowId;
public static PatientRecordEntity newPatient1;
public void generationRecord(){
newRowId = 0;
PatientRecordEntity newPatient1 = new PatientRecordEntity();
newPatient1.setPatient_db_ID("23456");
newPatient1.setPatient_race("Chines");
newRowId = (int) patientDao.addNewPatient(newPatient1);
newPatient1.setPid(newRowId);
}
#Test
public void addNewPatient() throws Exception {
boolean pin = false;
if (0 != newRowId) {
pin = true;
}
assertTrue("addNewPatient is not true", pin);
}
use the annotation #Before.
like:
public class HTest {
public static Integer i;
#Before
public void before(){
i = 10;
}
#Test
public void print() {
System.out.println(i);
}
}
This before method will be executed before print and i will be Initialized.
Related
I have a scenario as follows that I'm not sure from where to start,
File name should be passed as an argument param when running the jar file
say for example I want to test a set of data from external file and I have a super class (Test Suite) that have number one and number two
and there are two test classes that should extend this class and perform the tests.
I'm currently new to JUnit so I'm lacking many concepts and need someone's help.
I have class CoreManager which executes the main
public static void main(String[] args)
{
if (Arrays.asList(args).contains("Import"))
{
accountInfo = new ArrayList<>();
int ImportIndex = Arrays.asList(args).indexOf("Import");
String fileName = args[ImportIndex+1];
if (fileName.contains("xml"))
{
ParseXML parseXML = new ParseXML();
accountInfo = parseXML.ParseAccounts(fileName);
Result result = JUnitCore.runClasses(LoginTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
}
And Suite Class
#RunWith(MockitoJUnitRunner.class)
#Suite.SuiteClasses({
Login.class,
SignUp.class
})
public class LoginTestSuite {
public static WebDriver driver;
public static ArrayList<AccountInfo> Account;
public static int SecondsToWait;
public LoginTestSuite(WebDriver driver,ArrayList<AccountInfo> Account,int
secondsToWait)
{
this.Account = Account;
this.SecondsToWait = secondsToWait;
this.driver = driver;
}
}
And Test Class
public class Login {
private static WebDriver driver;
private static ArrayList<AccountInfo> Account;
private static int SecondsToWait;
private static final Logger logger = Logger.getLogger(Login.class.getName());
#BeforeClass
public void init(){
this.driver = LoginTestSuite.driver;
this.Account = LoginTestSuite.Account;
this.SecondsToWait = LoginTestSuite.SecondsToWait;
}
#Before
public void Setup(){
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(SecondsToWait,
TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(SecondsToWait,
TimeUnit.SECONDS);
}
#After
public void TearDown(){
driver.quit();
}
#Test
public void TestUserLogin() throws Exception
{
// Logic
}
Your code looks muddled and contains several poor quality constructs. Most importantly, I don't see a distinction between test code and production code. Which is which?
This could be production code:
public class App {
public static void main(String[] args) {
AccountReader accountReader = new AccountReader();
List<AccountInfo> accounts = accountReader.read(args);
// maybe do something with those accounts?
}
}
public class AccountReader {
private ParseXML parseXML;
public AccountReader() {
this.parseXML = new ParseXML();
}
// extra constructor to allow dependency injection from test
protected AccountReader(ParseXML parseXML) {
this.parseXML = parseXML;
}
public List<AccountInfo> read(String[] args) {
return parseXML.ParseAccounts(getFileName(args));
}
private String getFileName(String[] args) {
List<String> arguments = Arrays.asList(args);
int importIndex = arguments.indexOf("Import");
if (importIndex < 0) {
throw new RuntimeException("Missing Import argument");
}
int fileNameIndex = importIndex + 1;
if (fileNameIndex >= arguments.size()) {
throw new RuntimeException("Missing fileName argument");
}
String fileName = args[fileNameIndex];
if (!fileName.endsWith(".xml")) {
throw new RuntimeException("Can only import XML files");
}
return fileName;
}
}
And this could be a test for it:
public AccountReaderTest {
private AccountReader instance;
#Mock // creates a mock instance which we can give desired behavior
private ParseXML parseXML;
#Mock
List<AccountInfo> accounts;
#Before
public void setUp() {
instance = new AccountReader(parseXML);
}
#Test
public void testHappy() {
// SETUP
String fileName = "test.xml";
// specify desired behavior of mock ParseXML instance
when(parseXML.ParseAccounts(fileName).thenReturn(accounts);
// CALL
List<AccountInfo> result = instance.read(new String[] { "Import", fileName });
// VERIFY
assertEquals(accounts, result);
}
#Test(expected = RuntimeException.class)
public void testMissingImport() {
instance.read(new String[] { "notImport" });
}
#Test(expected = RuntimeException.class)
public void testMissingFileName() {
instance.read(new String[] { "Import" });
}
#Test(expected = RuntimeException.class)
public void testNotXml() {
instance.read(new String[] { "Import", "test.properties"});
}
}
I am using the Mocktio library to write some test cases, since I have an elaborate inhertance structure, I have a few objects which are instantiated in the parent class, and I would like to mock one of its function call. Does Mockito library provide any way to spy on a already initialized object?
Also, the object is not directly instantiable.
Similar to the following -
public class A {
protected static MyObject a;
public static void someMethod() {
a = myObjectBuilder.createObj();
}
}
And another class B looks something similar to
class B extends A {
#BeforeClass
public static void setUpBeforeClass() {
someMethod();
}
#Test
public void mockTest() {
// now mock behavior of some method of MyObject a
// Missing line to spy object a.
Mockito.doReturn(false).when(a).xyz();
/* Now call some method that triggers a.xyz()
again, it is not a direct call,
there are multiple layer of abstraction
*/
}
}
Edit: I have tried the following and it does not work
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(false).when(mock_object).xyz();
Basically, don't do initialisation in BeforeClass, it runs only once but
you need to have new spy in each test, or you must "reinitialise" spy object
before each test.
Please examine this code:
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
class MyObject{
public String cos;
public MyObject(String cos) {
this.cos = cos;
}
public boolean xyz() {
return true;
}
}
class A {
protected static MyObject a;
public void someMethod() {
a = new MyObject("cccc");
}
}
public class B extends A {
#Before
public void setUpBeforeTest() {
someMethod();
}
#Test
public void mockTest() {
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(mock_object.xyz()).isFalse();
}
#Test
public void mockTest2() {
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(true).when(mock_object).xyz();
assertThat(mock_object.xyz()).isTrue();
}
}
If you want it your way, please change:
public void someMethod() {
a = myObjectBuilder.createObj();
}
into:
public static void someMethod() {
a = myObjectBuilder.createObj();
}
You can't call non static method from static initialiser #BeforeClass:
class A {
protected static MyObject a;
public static void someMethod() {
a = new MyObject("cccc");
}
}
public class B extends A {
#BeforeClass
public static void setUpBeforeClass() {
someMethod();
}
#Test
public void mockTest() {
MyObject mock_object = Mockito.spy(a);
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(mock_object.xyz()).isFalse();
}
#Test
public void mockTest2() {
MyObject mock_object = Mockito.spy(a);
// Here we replace original object with our spy
A.a = mock_object;
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(a.xyz()).isFalse();
}
}
Another example (in this case we replace object a with mock (spy is not needed):
class MyObject{
public String cos;
public MyObject(String cos) {
this.cos = cos;
}
public boolean xyz() {
return true;
}
}
class A {
protected MyObject a;
public A() {
a = new MyObject("ggggg");
}
public String doSomethingWithA(){
if(a.xyz()){
return a.cos;
}
else{
return "aaaa";
}
}
}
#RunWith(MockitoJUnitRunner.class)
public class B {
#Mock
MyObject mock_object;
#InjectMocks
A systemUnderTest = new A();
#Test
public void mockTest1() {
Mockito.doReturn(false).when(mock_object).xyz();
assertThat(systemUnderTest.doSomethingWithA()).isEqualTo("aaaa");
}
#Test
public void mockTest2() {
Mockito.doReturn(true).when(mock_object).xyz();
assertThat(systemUnderTest.doSomethingWithA()).isNull();
}
}
I have two class
public class xyzTest {
#Test
public void TestP1TUNG557(){
TestHelper.excuteTestcase(TUNG557);
Assert.assertTrue(TestHelper.TestResult);
}
#Test
public void TestP1TUNG559(){
TestHelper.excuteTestcase(TUNG559);
Assert.assertTrue(TestHelper.TestResult);
}
#Test
public void TestP0TUNG558(){
TestHelper.excuteTestcase(TUNG558);
Assert.assertTrue(TestHelper.TestResult);
}
}
public class TestHelper {
public excuteTestcase(String abc)
{
process(abc)
}
int TotalTescase(String pattern, Class testNGclass)
{
How to write here..? plz help
}
}
suppose if have called TotalTescase(String TestPO, Class xyzTest), it should return 1 and if have called TotalTescase(String TestP1, Class xyzTest) it should return 2.
If This is possible to get total test case like this ,plz help me or provide me some link
I have searched but i couldnt find. help me
You can use reflection technique to find out the matching methods in the supplied class like:
public int TotalTescase(String pattern, Class<?> testNGclass) throws ClassNotFoundException
{
int count = 0;
testNGclass.getClass();
Class<?> className = Class.forName(testNGclass.getName());
Method[] methods = className.getMethods();
for(int i=0; i<methods.length; i++)
{
String methodName = methods[i].getName();
System.out.println("Method Name: "+methodName);
if(methodName.contains(pattern))
{
count++;
}
}
return count;
}
In dry run try to implement IInvokedMethodListener and override beforeInvocation method
public class Test implements IInvokedMethodListener
{
static int testcount=0;
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
testcount=testcount+method.getTestMethod().getInvocationCount();
}
#Override
public void onStart(ISuite suite) {
// TODO Auto-generated method stub
}
#Override
public void onFinish(ISuite suite) {
System.out.println(testcount);
}
}
I'm having hard time to test a class(TestClass) which uses builder pattern(BuilderClass) in logic . I'm unable to mock builder class(BuilderClass). The following is simplified version of my logic.
public class TestClass {
public int methodA() {
ExternalDependency e = BuilerClass.builder().withName("xyz").withNumber(10).build();
return e.callExternalFunction();
}
}
And here is my builder class
public class BuilderClass {
public static BuilderClass builder() { return new BuilderClass(); }
int number;
String name;
public BuilderClass withName(String name) {
this.name = name;
return this;
}
public BuilderClass withNumber(int number) {
this.number = number;
return this;
}
public ExternalDependency build() {
return new ExternalDependency(name,number);
}
}
For my test class, I'm using Mockito with Dataprovider.
#RunWith(DataProviderRunner.class)
class TestClassTest {
#Mock private ExternalDependency e;
#Mock private BuilderClass b;
#InjectMocks private TestClass t;
#Before public void setUp() { MockitoAnnotations.initMocks(this); }
#Test public void testMethodA() {
when(b.withName(any(String.class)).thenReturn(b); //This is not mocking
when(b.withNumber(10)).thenReturn(b); //This is not mocking
Assert.notNull(this.t.methodA()); //Control while execution is going to implementation of withName and withNumber, which should not happen right.
}
Help me if I miss anything. Thanks
}
Similar to what kryger said in a comment above, you probably need to do a refactor like this:
In your class under test, create a seam to replace e by a mock:
public class TestClass {
public int methodA() {
ExternalDependency e = buildExternalDependency("xyz", 10);
return e.callExternalFunction();
}
protected ExternalDependency buildExternalDependency(String name, int number) {
return BuilerClass.builder().withName(name).withNumber(number).build();
}
}
In the test code, override the test class to replace e with a mock and to validate the inputs to the builder:
#RunWith(DataProviderRunner.class)
class TestClassTest {
#Mock private ExternalDependency e;
private TestClass t;
#Before public void setUp() {
MockitoAnnotations.initMocks(this);
t = new TestClass() {
#Override
protected ExternalDependency buildExternalDependency(String name, int number) {
// validate inputs:
Assert.assertEquals(10, number);
Assert.assertEquals("xyz", name);
return e; // provide the mock
}
}
}
#Test public void testMethodA() {
// TODO: mock behavior of callExternalFunction() here
Assert.notNull(this.t.methodA());
}
}
You may want to go further with the refactor to move buildExternalDependency() into a another class which could be mocked and injected in the constructor of TestClass.
want to use non static method in static main, but i cant. I know this problem but, because i use INotificationObserver, i cant make registerObserver as static. So i could solve my problem.
How can i solve this problem ?? Thanks .
non-static variable this cannot be referenced from a static context
Test
public class PushTest implements INotificationObserver{
NotificationService ns = NotificationService.getInstance();
public static void main(String[] args) {
try {
ns.registerObserver(this); // How can i register ???
Interface
public interface INotificationSubject {
public void registerObserver(INotificationObserver o);
public void removeObserver(INotificationObserver o);
public void notifyObserver(PushedNotification notification);
}
*NotificationService *
public class NotificationService implements INotificationSubject{
protected static final Logger logger = Logger.getLogger(NotificationService.class);
private volatile static NotificationService uniqueFactory;
private ArrayList observers;
private NotificationService() {
observers = new ArrayList();
}
public static NotificationService getInstance() {
if (uniqueFactory == null) {
synchronized (NotificationService.class) {
if (uniqueFactory == null) {
uniqueFactory = new NotificationService();
}
}
}
return uniqueFactory;
}
public static INotification GetNotificationObject(DeviceTypes Types) {
INotification messageSender = null;
if (Types == Types.IOS) {
messageSender = new IosNotification();
}
return messageSender;
}
public void registerObserver(INotificationObserver o) {
observers.add(o);
}
public void removeObserver(INotificationObserver o) {
int i =
observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObserver(PushedNotification notification) {
for (int i = 0; i < observers.size(); i++) {
INotificationObserver observer = (INotificationObserver) observers.get(i);
observer.update(notification);
}
}
public void messageSendInfo(PushedNotification notification) {
notifyObserver(notification);
}
public void showSentInfo(PushedNotification notification) {
messageSendInfo(notification);
}
}
You need an instance:
INotificationObserver ino = new PushTest();
ns.registerObserver(ino);
Therefor, you don't need the ns attribute.
typical solution for this is initialize your class in the main method:
public class PushTest implements INotificationObserver{
NotificationService ns = NotificationService.getInstance();
public static void main(String[] args) {
PushTest pushTest = new Pushtest();
...
etc etc