gpt4 book ai didi

unit-testing - 干燥 EasyMock 测试

转载 作者:行者123 更新时间:2023-11-28 21:13:48 26 4
gpt4 key购买 nike

EasyMock 测试似乎倾向于遵循以下模式:

@Test
public void testCreateHamburger()
{
// set up the expectation
EasyMock.expect(mockFoodFactory.createHamburger("Beef", "Swiss", "Tomato", "Green Peppers", "Ketchup"))
.andReturn(mockHamburger);

// replay the mock
EasyMock.replay(mockFoodFactory);

// perform the test
mockAverager.average(chef.cookFood("Hamburger"));

// verify the result
EasyMock.verify(mockFoodFactory);
}

这对于一次测试来说效果很好,但是当我想用不同的方法再次测试相同的逻辑时会发生什么?我的第一个想法是做这样的事情:

@Before
public void setUp()
{
// set up the expectation
EasyMock.expect(mockFoodFactory.createHamburger("Beef", "Swiss", "Tomato", "Green Peppers", "Ketchup"))
.andReturn(mockHamburger);

// replay the mock
EasyMock.replay(mockCalculator);
}

@After
public void tearDown()
{
// verify the result
EasyMock.verify(mockCalculator);
}

@Test
public void testCreateHamburger()
{
// perform the test
mockAverager.average(chef.cookFood("Hamburger"));
}

@Test
public void testCreateMeal()
{
// perform the test
mockAverager.average(chef.cookMeal("Hamburger"));
}

这种方法存在一些基本问题。首先是我的方法调用不能有任何变化。如果我想测试 person.cookFood("Turkey Burger"),我的设置方法将不起作用。第二个问题是我的设置方法需要调用 createHamburger。如果我调用 person.cookFood("Salad"),那么这可能不适用。我可以在 EasyMock 中使用 anyTimes()stubReturn() 来避免这个问题。但是,这些方法仅验证方法是否被调用,是否使用特定参数调用,而不是方法是否实际被调用

目前唯一有效的解决方案是复制并粘贴每个测试的期望值并改变参数。 有没有人知道使用 EasyMock 进行测试的更好方法,同时保持 DRY 原则?

最佳答案

您遇到的问题是因为单元测试应该是 DAMP not DRY .单元测试往往会 self 重复。如果你能以一种安全的方式删除重复(这样它就不会创建不必要的耦合测试),那就去做吧。如果没有,那就不要强制它。单元测试应该快速而简单……如果不是,那么您将花费太多时间进行测试,而不是编写业务值(value)。

只是我的两分钱。 BTW, the Art of Unit Testing by Roy Osherove是一本关于单元测试的好书,涵盖了这个主题。

关于unit-testing - 干燥 EasyMock 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11266765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com