简体   繁体   English

JUnit测试-类调用其他类中的方法

[英]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. 因此feedPet调用宠物的eat方法,然后eat方法调整宠物的饥饿程度。

To test this I need create a player and food object in my jUnit test case. 为了测试这一点,我需要在我的jUnit测试用例中创建一个玩家和食物对象。

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. p1是我在播放器测试用例中创建的宠物对象。

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. 真的可以测试宠物的eat方法是否有效,但我还需要检查feedPet方法是否也适用于玩家。

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 . 您并不是真正测试Pet.eat()方法,而是PlayerPet之间的正确交互。

You might also need a separate test for Pet class to cover more cases. 您可能还需要针对Pet类的单独测试,以涵盖更多案例。

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. 理想情况下,您应该创建两个测试文件-一个用于测试其eat方法的Pet类,另一个用于测试feedPet方法的播放器类。

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 我希望饥饿是在宠物类的eat方法下设置的实例变量,按照您的期望,该变量为3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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