Parameterized Singleton class test - junit

I am writing test case for Singleton class. But call is going to original dependency.
Mock injection is not working for Math and Art.
private final Math math;
private final Art art;
private final tot;
private Student(Math math, Art art){
this.math = math;
this.art = art;
}
public static Student getInstance() {
Student st= new Student(new Mant(), new Art());
st.display();
return st;
}
public void display() {
tot = math.getScore() + art.getScore();
}
}
Test class
public class StudentTest{
#Test
#PrepareForTest(Student.class)
void testDisplay() {
Math mockMath = PowerMockito.mock(Math.class);
PowerMockito.when(mockMath.getScore()).thenReturn(80);
Math mockArt = PowerMockito.mock(Art.class);
PowerMockito.when(mockArt.getScore()).thenReturn(70);
Student mst= Student.getInstance();
mst.display();
assertEquals(mst.tot(), 150);
}
}

Add the #RunWith(PowerMockRunner.class) annotation to your test class
#RunWith(PowerMockRunner.class)
public class StudentTest{
#Test
#PrepareForTest(Student.class)
void testDisplay() {
Math mockMath = PowerMockito.mock(Math.class);
PowerMockito.when(mockMath.getScore()).thenReturn(80);
Math mockArt = PowerMockito.mock(Art.class);
PowerMockito.when(mockArt.getScore()).thenReturn(70);
Student mst= Student.getInstance();
mst.display();
assertEquals(mst.tot(), 150);
}
}

Related

NPE related to Artemis in Libgdx project

Update:
WorldConfiguration and World are still the same,
WorldConfiguration setup = new WorldConfigurationBuilder()
.with(new HelloSystemArtemis())
.with(new RenderSystem(batch, environment))
.with(new BulletSystem(this))
.with(new PlayerSystem(perspectiveCamera, batch, gameUi, this))
.with(new AthmosphereSystem(modelComponent,
bulletComponent))
.with(new MovementSystem(this))
.with(new StatusSystem(this))
.with(new EnemySystem(this))
.build();
World world = new World(setup);
world.setDelta(delta);
int entityId = world.create();
world.edit(entityId).create(HelloComponentArtemis.class).message = "\n\rHello Oxyddians!\n\r";
Decided to post full code for clarity reason, in fact can't explain from where the problem is coming, even if I got errors that point me to
#All({ModelComponentArtemis.class, ModelComponentArtemis.class})
public class AthmosphereSystem extends BaseSystem {
private static OxyddiA game;
private static Assets assets = new Assets();
private ComponentMapper<ModelComponentArtemis> mc;
private ComponentMapper<BulletComponentArtemis> bc;
public AthmosphereSystem(ComponentMapper<ModelComponentArtemis> mc,
ComponentMapper<BulletComponentArtemis> bc) {
this.mc = mc;
this.bc = bc;
}
#Override
protected void processSystem() {
int entity = world.create();
ModelComponentArtemis mc = new ModelComponentArtemis(assets.Athmosphere,0,0,0);
mc.create(entity); //Not working
BulletComponentArtemis bc = new BulletComponentArtemis();
btCollisionShape shape = Bullet.obtainStaticNodeShape(assets.Athmosphere.nodes);
bc.bodyInfo = new btRigidBody.btRigidBodyConstructionInfo(0, null, shape, Vector3.Zero);
bc.body = new btRigidBody(bc.bodyInfo);
bc.body.userData = entity;
bc.motionState = new MotionState(mc.instance.transform);
((btRigidBody) bc.body).setMotionState(bc.motionState);
bc.create(entity); //Not working
return entity; //Not working as well
}
}
ModelComponent used in this approach
public class ModelComponentArtemis extends Component {
public Model model;
public ModelInstance instance;
public ModelComponentArtemis(Model model, float x, float y, float z)
{
this.model = model;
this.instance = new ModelInstance(model, new Matrix4().setToTranslation(x, y, z));
}
public void reset() {
}
}
BulletComponent used in this approach
public class BulletComponentArtemis extends Component {
public MotionState motionState;
public btRigidBody.btRigidBodyConstructionInfo bodyInfo;
public btCollisionObject body;
public Model model;
public void init() {
ModelComponentArtemis modelComponent = new ModelComponentArtemis(model,0,0,0);
BulletComponentArtemis bulletComponent = new BulletComponentArtemis();
btCollisionShape shape = Bullet.obtainStaticNodeShape(model.nodes);
bulletComponent.bodyInfo = new btRigidBody.btRigidBodyConstructionInfo(0, null, shape, Vector3.Zero);
bulletComponent.body = new btRigidBody(bulletComponent.bodyInfo);
Object bCuD = null;
bulletComponent.body.userData = bCuD;
bulletComponent.motionState = new MotionState(modelComponent.instance.transform);
((btRigidBody) bulletComponent.body).setMotionState(bulletComponent.motionState);
}
public void reset() {
}
}
And of course the BulletSystem used in this project
#All(ModelComponentArtemis.class)
public class BulletSystem extends EntitySystem
{
public Entity e;
public final btCollisionConfiguration collisionConfiguration;
public final btCollisionDispatcher dispatcher;
public final btBroadphaseInterface broadphase;
public final btConstraintSolver solver;
public final btDiscreteDynamicsWorld collisionWorld;
public GameWorld gameWorld;
public PreGameWorld preGameWorld;
private final btGhostPairCallback ghostPairCallback;
public final int maxSubSteps = 5;
public final float fixedTimeStep = 0.2f / 60f;
private EntityContactListener myContactListener;
public BulletSystem(GameWorld gameWorld)
{
super(Aspect.all(ModelComponentArtemis.class));
this.gameWorld = gameWorld;
myContactListener = new EntityContactListener();
myContactListener.enable();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
broadphase = new btAxisSweep3(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000));
solver = new btSequentialImpulseConstraintSolver();
collisionWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
ghostPairCallback = new btGhostPairCallback();
broadphase.getOverlappingPairCache().setInternalGhostPairCallback(ghostPairCallback);
this.collisionWorld.setGravity(new Vector3(0f, -0.5f, 0f));
}
public BulletSystem(PreGameWorld preGameWorld)
{
this.preGameWorld = preGameWorld;
myContactListener = new EntityContactListener();
myContactListener.enable();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
broadphase = new btAxisSweep3(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000));
solver = new btSequentialImpulseConstraintSolver();
collisionWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
ghostPairCallback = new btGhostPairCallback();
broadphase.getOverlappingPairCache().setInternalGhostPairCallback(ghostPairCallback);
this.collisionWorld.setGravity(new Vector3(0f, -0.5f, 0f));
}
public void update(float deltaTime)
{
collisionWorld.stepSimulation(deltaTime, maxSubSteps, fixedTimeStep);
}
protected void processSystem(int entityId) {
this.world.getEntity(entityId).getComponent(BulletComponentArtemis.class);
}
#Override
protected void processSystem() {
}
public void dispose()
{
collisionWorld.dispose();
if (solver != null) solver.dispose();
if (broadphase != null) broadphase.dispose();
if (dispatcher != null) dispatcher.dispose();
if (collisionConfiguration != null)
collisionConfiguration.dispose();
ghostPairCallback.dispose();
}
}
With all that in mind, I know I just can't find any solution,
Maybe it will be clearer like that for anyone wishing to help
Thanks anyawy.
Couple of things to note:
you don't need to inject entity instances
working with Entity and EntityEdit is slower than working with int and ComponentMapper/Archetype/EntityTransmuter, but fine for the beginning.
What you probably want to do is creating an AtmosphereSystem (extending BaseSystem) and create the entity within the initialize method or offer a public method (non-static).
If you need to call those entity factory methods, just inject the AtmosphereSystem (or anything extending BaseSystem) by adding a field "AtmosphereSystem atmosphereSytem;" inside any other BaseSystem.
See this gist for a similar use case (factory methods for creating entities).

Mocking the object inside the class without PowerMock

I want to mock the object inside the class wihtout using Powermock. How can I do it?
I tried using spy but it didn't work.
/** SOURCE CODE **/
abstract class Parent {
protected final Caller caller = new Caller();
public abstract void call(Connection, Integer);
}
class Child1 extends Parent {
#Override
public void call(Connection con, Integer id1) {
// some logic
caller.getSomething1(connection, id1);
}
}
class Child2 extends Parent {
#Override
public void call(Connection con, Integer id2) {
// some logic
caller.getSomething2(connection, id2);
}
}
class Activity {
#Inject
private MyConnection connection;
public Response process(Request r) {
Parent p = ChildFactory.getChild(r); // returns a child based on some logic related to p
p.call(connection, r.getId());
return new Response("SUCCESS");
}
}
/** TEST CODE **/
public class Test {
#InjectMocks
private Activity activity;
#Mock
private Connection connectionMock;
private Caller caller;
#Before
public void setup() throws Exception {
caller = Mockito.spy(Caller.class);
Mockito.doReturn(null).when(caller).getSomething1(Mockito.any(), Mockito.any());
Mockito.doReturn(null).when(caller).getSomething2(Mockito.any(), Mockito.any());
}
#Test
public void testProcess() {
Request r = new Request(1);
Response r = activity.process(r);
Assert.assertEquals(r.getResult(), "SUCCESS");
}
}
I want to mock the caller object created in Parent class. It is going to be consumed by every children. I am not bothered about the result of the calls so I want to mock all calls (i.e. getSomething1, getSomething2) of callers without use of PowerMock.
I tried using spy but it is not using the spied object and it is calling getSomething1 and getSomething2 methods.
You can use ReflectionTestUtils#setField
#Before
public void setup() throws Exception {
caller = Mockito.spy(Caller.class);
Mockito.doReturn(null).when(caller).getSomething1(Mockito.any(), Mockito.any());
Mockito.doReturn(null).when(caller).getSomething2(Mockito.any(), Mockito.any());
// ... obtain children here ...
ReflectionTestUtils.setField(child1, "caller", caller);
ReflectionTestUtils.setField(child2, "caller", caller);
}
Or better you don't instantiate Caller instance inside Child-classes but inject via constructor for example

JUnit mocking method call

I am writing a Junit test for a method 'methodA' which is in class 'classA'. In 'methodA' another method 'methodB' of class 'classB' is called. The 'methodB' calls soap web-service. I want to mock this methodB soap web-service call. In this case i am calling classA.methodA. Here i don't find a way that at the time when classB.methodB is called then mock value should get updated. I went through many links about Mockito, but they all refer on updating the mock value from junit class only. So, how can i pass mocked value their.
#Test
public void junitTest() {
String arg1 = "arg1";
classA aObj = new classA();
aObj.methodA(arg1);
}
public classA {
public string methodA(String arg1) {
classB bObj = new classB();
bObj.methodB();
//somwthing on arg1
return result;
}
}
public classB {
public list methodB() {
//web-service call
return list from web - service.
}
}
I am writing a Junit test for a method methodA which is in class
classA
Since you are unit testing methodA of classA, you should be focusing on mocking just the bObj.methodB(); call. You should not get into what it does or doesn't internally.
Not you are creating classB object in methodA which is not the ideal scenario. You should make bObj as the instance variable of classA with appropriate getter, setters and constructor.
Then from you testing class set this classB dependency.
You should structure your code and something tests like this:
class classAMicroTest {
#Test
public void junitTest() {
String arg1 = "arg1";
classA aObj = new classA();
classB mockedBobj = Mockito.mock(classB.class);
Mockito.when(mockedBobj.methodB()).thenReturn(new ArrayList<>());
aObj.setbObj(mockedBobj);
aObj.methodA(arg1);
Mockito.verify(mockedBobj, times(1)).methodB());
}
}
class classA {
classB bObj;
public void setbObj(classB bObj) {
this.bObj = bObj;
}
public String methodA(String arg1) {
bObj.methodB();
// somwthing on arg1
return result;
}
}
class classB {
public List<String> methodB() {
return new ArrayList<>();
}
}

Unit test WCMUsePOJO class

I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
#Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
#Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
#Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
#Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
#Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
The only thing that you should "have to"* mock is the SlingScriptHelper instance itself, so that it will mimic the dependency injection of the declared service.
Everything else (e.g. the Bindings instance) can be a concrete implementation, for example:
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.junit.Test;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConstantsServiceProviderTest {
private SlingScriptHelper mockSling = mock(SlingScriptHelper.class);
private ConstantsServiceProvider constantsServiceProvider = new ConstantsServiceProvider();
private Bindings bindings = new SimpleBindings();
#Test
public void testFoo() throws Exception {
//Arrange
final String expected = "Hello world";
final ConstantsService testConstantsService = new TestConstantsService(expected);
when(mockSling.getService(ConstantsService.class)).thenReturn(testConstantsService);
bindings.put(SlingBindings.SLING, mockSling);
//Act
constantsServiceProvider.init(bindings);
//Assert
final String actual = constantsServiceProvider.getVar1();
assertThat(actual, is(equalTo(expected)));
}
class TestConstantsService extends ConstantsService {
String var1 = "";
TestConstantsService(String var1) {
this.var1 = var1;
}
#Override
String getVar1() {
return var1;
}
}
}
The entry point here, as you said above, is via the init() method of the WCMUsePojo superclass (as this method is an implementation of the Use.class interface, this test structure also works for testing that via that interface, even if you don't use WCMUsePojo directly.)
*this could be any type of test-double, not necessarily a mock.
You shouldn't create a mock for ConstantsServiceProvider.class if you want to unit-test it. Instead, you should create mocks of its internal objects. So:
Create real instance of ConstantsServiceProvider with new
Mock objects that are returned by getSlingScriptHelper().getService(.) methods. Usually, dependencies are provided (injected) to classes by some container like Spring or simply provided by other classes of your app using setters. In both cases mocks creation is easy.
If your current implementation doesn't allow this - consider refactoring.
You are testing void activate() method which doesn't return anything. So, you should verify calling constantsService.getVar1() method.
I strongly advice you to study Vogella unit-testing tutorial
Here one of possible solution.
The main idea is to have a real object of your class but with overridden getSlingScriptHelper() to return mocked scriptHelper.
I mocked the ConstantsService as well but may be not needed, I don't know your code.
public class ConstantsServiceProviderTest {
#Mock
public SlingScriptHelper scriptHelper;
#Test
public void getVar1ReturnsActivatedValue() throws Exception {
// setup
final String expectedResult = "some value";
// Have a mocked ConstantsService, but if possible have a real instance.
final ConstantsService mockedConstantsService =
Mockito.mock(ConstantsService.class);
Mockito.when(
mockedConstantsService.getVar1())
.thenReturn(expectedResult);
Mockito.when(
scriptHelper.getService(ConstantsService.class))
.thenReturn(mockedConstantsService);
// Have a real instance of your class under testing but with overridden getSlingScriptHelper()
final ConstantsServiceProvider providerWithMockedHelper =
new ConstantsServiceProvider() {
#Override
SlingScriptHelper getSlingScriptHelper() {
return scriptHelper;
}
};
// when
String actualResult = providerWithMockedHelper.getVar1();
// then
assertEquals(expectedResult, actualResult);
}
}

How to use mockito for implement dummy?

I have simple code:
public interface AccountService {
public boolean verifyBalance(AccountInfo account);
}
public class MoneyTransferServiceBean implements MoneyTransferService {
private AccountService accountService;
class MoneyTransfer {
private TransferRequest request;
public MoneyTransfer(TransferRequest request) {
this.request = request;
}
private void verifySrcBalance() throws TransferException {
if (!accountService.verifyBalance("request")
throw new TransferException("LOW_BALANCE_ERROR_MESSAGE");
}
}
}
How Im make implement dummy for accountService.verifyBalance()
Im trying this:
private MoneyTransferServiceBean moneyTransferService;
AccountService mockedAccountService = mock(AccountService.class);
doReturn(true).when(mockedAccountService).verifyBalance("request");
MoneyTransfer moneyTransfer = moneyTransferService.new MoneyTransfer(transferRequest);
moneyTransfer.verifySrcBalance();
But this does not take effect.
generaly doX() methods are used for mocking exception throws and void methods.
Other use is mocked by when([method_call]).thenX();
First create mocks and put your mock into tested service with setters or Whitebox:
MoneyTransferServiceBean moneyTransferService = new MoneyTransferServiceBean();
AccountService mockedAccountService = mock(AccountService.class);
Whitebox.setInternalState(moneyTransferService , "accountService", mockedAccountService);
You should mock interaction with the mock like this:
when(mockedAccountService.verifyBalance(eq(accInfo)).thenReturn(true);
verify(mockedAccountService).verifyBalance(accInfo);
verifyNoMoreInteractions(mockedAccountService);
There are nice examples on Mockito site explaining it all.