简体   繁体   中英

JUnit Test - Class invokes methods in other class

I have a class player which has a method

 feedPet(Pet p1, Food f1){
 p1.eat(f1) 
 }

So the feedPet invokes the pets eat method, the eat method then adjusts the pets hunger level.

To test this I need create a player and food object in my jUnit test case.

I then test that its working with a simple

 assertEquals(p1.getHunger,3);

p1 is the pet object I have created in the player test case.

My question is , is what I am doing appropriate? and am I testing my player class correctly?

Really Its testing if the eat method for the pet works but I also need to check that the feedPet method works for the player as well.

Any thoughts or advice is much appreciated.

Assuming your test looks something like that

@Test
public void player_should_feed_a_pet() {
    Food f1 = givenFoodWithHungerReductionOf(1);
    Pet p1 = givenPetWithHunger(4);
    player.feedPet(p1, f1);
    assertEquals(p1.getHunger(), 3);
}

It is a good test. You're not really testing the Pet.eat() method, but the correct interactions between Player and Pet .

You might also need a separate test for Pet class to cover more cases.

What you should do ideally is to create two test files -one for Pet class that tests its eat method and another for player class which tests feedPet Method.

When you write

assertEquals(p1.getHunger,3);

I hope hunger is the instance variable that was set under eat method of pet class, which as per your expectation is 3. If that's the case you are on right path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM