BAEL-6332: Calling Non-Static Method In Static Method In Java (#13940)

This commit is contained in:
ACHRAF TAITAI 2023-05-05 22:25:50 +02:00 committed by GitHub
parent 7e404b3dfb
commit 3ab60dc307
3 changed files with 32 additions and 0 deletions

View File

@ -42,6 +42,10 @@ public class Car {
this.engine = engine;
}
public static String getCarsInformation(Car car) {
return car.getName() + "-" + car.getEngine();
}
public static void setNumberOfCars(int numberOfCars) {
Car.numberOfCars = numberOfCars;
}

View File

@ -0,0 +1,21 @@
package com.baeldung.staticmethod;
import static org.junit.Assert.assertEquals;
import org.junit.AfterClass;
import org.junit.Test;
import com.baeldung.staticmodifier.Car;
public class CallNonStaticMethodUnitTest {
@AfterClass
public static void setUpCarInstance() {
Car.setNumberOfCars(0);
}
@Test
public void whenCallingNonStaticMethodInStaticMethodWithInstanceClass_thenSuccess() {
Car car = new Car("Jaguar", "V8");
assertEquals("Jaguar-V8", Car.getCarsInformation(car));
}
}

View File

@ -2,9 +2,16 @@ package com.baeldung.staticmodifier;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Test;
public class CarUnitTest {
@AfterClass
public static void setUpCarInstance() {
Car.setNumberOfCars(0);
}
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");