如何为arraylist编写Junit测试用例(按位置检索数据)??请更喜欢以下代码

时间:2015-05-27 06:05:19

标签: java arraylist junit

这是完整的代码。我需要写一个测试用例。请帮我写出测试用例,我是初学者,也是Junit的新手。

import socket, select, string, sys, time

def prompt(data) :
     print("<You> " + data)
def Person(data) :
    print("<Receiver> " + data)

if __name__ == "__main__":

    host = "localhost"
    port = 5558

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)

    try:
        s.connect((host,port))
    except:
        print('Unable to connect')
        sys.exit()
    print('Connected.')
    socket_list = [s]
    read_sockets,write_sockets,error_sockets = select.select(socket_list,[],[])
    while 1:
        for sock in read_sockets:
            if sock == s:
                try:
                    time.sleep(1)
                    data = sock.recv(1024)             
                    Person(data.decode("utf-8"))
                except:
                    msg = input("Send a message: ")
                    try:
                        s.send(str.encode(msg))
                    except:
                        print("Server is offline")
                        sys.exit()


            else:
                print("Server is offline")
                sys.exit()

输出:

来自伦敦的员工:800伦敦101杰克

来自伦敦的员工:90000 London 102 Donald

1 个答案:

答案 0 :(得分:0)

首先,我将程序的“逻辑”部分提取到一个单独的方法:

public static List<Register1> filtrerByLocation (List<Register1> emp, String location) {
     List<Register1> reg = new ArrayList<Register1>();

     // A for loop would be nicer, IMHO, but keeping OP's style
     Iterator<Register1> itr = emp.iterator(); 
     while (itr.hasNext()) {
        Register1 res = (Register1) itr.next();
        if (res.location.equals("London")) {
            reg.add(res);
        }
     }
}

现在,您可以轻松地为它编写测试套件。以给定的main

为例
@Test
public void testFiler() {
    List<Register1> emp = new ArrayList<Register1>();
    emp.add(new Register1("Jack", "London", 101, 800));
    emp.add(new Register1("Mike", "UK", 100, 60000));
    emp.add(new Register1("Andrew", "China", 103, 2000));
    emp.add(new Register1("Michel", "Korea", 106, 300000));
    emp.add(new Register1("Donald", "London", 102, 90000));

    List<Register1> res = filterByLocation(emp, "London");

    assertEquals (2, res.size());
    assertEquals ("Jack", res.get(0).getName());
    assertEquals ("Donald", res.get(1).getName());
}