gpt4 book ai didi

java - 如何使用嵌套的for循环测试方法

转载 作者:行者123 更新时间:2023-11-30 05:51:48 24 4
gpt4 key购买 nike

我是单元测试的初学者。我使用 JUnit 和 Mockito。这是我要测试的一种示例方法。

public List<Person> getPeopleList(List<Aggregate<Person>> aggregateList) {
List<Person> resultList = new ArrayList<Person>();
for (Aggregate<Person> aggregate : aggregateList) {
resultList.add(aggregate);

for (Person person : aggregate) {
resultList.add(person);
}
}
return resultList; // the result is person and aggregate list
}

我尝试了很多方法,但我做不好。示例:

@Test
public void getPeopleListTest(){
ClassUnderTest testedClass = new ClassUnderTest();

Aggregate aggregate = mock(Aggregate.class);
Iterator<Aggregate<Person>> aggregateIterator = mock(Iterator.class);
when(aggregateIterator.hasNext()).thenReturn(true, false);
when(aggregateIterator.next()).thenReturn(aggregate);

List<Aggregate<Person>> aggregateList = mock(List.class);

aggregateList.add(aggregate);

List<Person> list = testedClass.getPeopleList(aggregateList);

assertEquals(1, list.size());
}

提前谢谢你。

最佳答案

我不会 mock 所有可能的事情。我只会模拟您要测试的类并假设 List 行为正确。

public class Main {
interface Person {
}

interface Aggregate<T> extends Person, Iterable<T> {
}

public static List<Person> getPeopleList(List<Aggregate<Person>> aggregateList) {
List<Person> resultList = new ArrayList<Person>();
for (Aggregate<Person> aggregate : aggregateList) {
resultList.add(aggregate);

for (Person person : aggregate) {
resultList.add(person);
}
}
return resultList; // the result is person and aggregate list
}

public static void main(String... args) {
Aggregate<Person> aggregate = mock(Aggregate.class);
Aggregate<Person> aggregate2 = mock(Aggregate.class);
Person person = mock(Person.class);
Person person2 = mock(Person.class);
when(aggregate.iterator()).thenReturn(Arrays.asList(person).iterator());
when(aggregate2.iterator()).thenReturn(Arrays.asList(person2).iterator());

List<Person> list = getPeopleList(
Arrays.asList(aggregate, aggregate2));
System.out.println(list);
System.out.println("size: " + list.size());
}
}

打印

[Mock for Aggregate, hashCode: 2037567902, Mock for Person, hashCode: 1629493852, Mock for Aggregate, hashCode: 44220373, Mock for Person, hashCode: 182467149]
size: 4

关于java - 如何使用嵌套的for循环测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12459041/

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