模拟模拟方法的副作用
我在一个类中有一个方法,该方法会对方法的参数产生副作用:
public void SideEffectsClass {
public void doSomethingWithSideEffects(List<Object> list) {
// do something to the list
}
}
并且正在测试该类:
public void ClassUnderTest() {
public List<Object> execute() {
List<Object> results = new ArrayList<Object>();
new SideEffectsClass().doSomethingWithSideEffects(results);
return results;
}
}
我使用 JMockit 的测试方法:
@Test
public void test() throws Exception
{
// arrange
new Expectations()
{
SideEffectsClass sideEffects;
{
new SideEffectsClass();
sideEffects.doSomethingWithSideEffects((List<Object>) any);
// I want to simulate that the List<Object> parameter has changed
// (has more elements, less elements, etc. after this method is called
}
};
// act
ClassUnderTest testClass = new ClassUnderTest();
List<Object> results = testClass.execute();
// assert
Assert.assertEquals(myExpectedResults, results);
}
I have a method in a class that causes side effects to the method's parameter:
public void SideEffectsClass {
public void doSomethingWithSideEffects(List<Object> list) {
// do something to the list
}
}
And this class being tested:
public void ClassUnderTest() {
public List<Object> execute() {
List<Object> results = new ArrayList<Object>();
new SideEffectsClass().doSomethingWithSideEffects(results);
return results;
}
}
My test method using JMockit:
@Test
public void test() throws Exception
{
// arrange
new Expectations()
{
SideEffectsClass sideEffects;
{
new SideEffectsClass();
sideEffects.doSomethingWithSideEffects((List<Object>) any);
// I want to simulate that the List<Object> parameter has changed
// (has more elements, less elements, etc. after this method is called
}
};
// act
ClassUnderTest testClass = new ClassUnderTest();
List<Object> results = testClass.execute();
// assert
Assert.assertEquals(myExpectedResults, results);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Delegate
对象来更改参数值:如果您需要的只是验证是否调用了
doSomethingWithSideEffects
方法,那么测试可以更简单地编写为:You can use a
Delegate
object to change an argument value:If all you need is to verify that the
doSomethingWithSideEffects
methods was called, then the test could be written more simply as:正如测试试图告诉您的那样,副作用不是 ClassUnderTest 行为的一部分。不要尝试在这里测试它。根据您显示的代码,您应该测试的只是将
results
传递给doSomethingWithSideEffects()
并且从execute( 返回相同的对象)
。由于不熟悉 JMockit 语法,我无法准确告诉您如何编写它。旁白:不过,我确实建议每个使用 jMock、JMockit 或 EasyMock 等工具的人都应该使用 Mockito,如果他们能。
As the test is trying to tell you, the side effects aren't part of the behavior of ClassUnderTest. Don't try to test that here. Based on the code you're showing, all you should be testing is that
results
is passed todoSomethingWithSideEffects()
and that the same object is returned fromexecute()
. Being unfamiliar with JMockit syntax, I can't tell you exactly how to write it.Aside: I do recommend, however, that everyone using a tool like jMock, JMockit, or EasyMock should use Mockito instead if they can.