在 Eclipse 中使用 TestNG 编写单元测试

Write unit tests with TestNG in Eclipse

class MobileStorage 是复古手机 phone 收件箱的实现。因此,收件箱被定义为保存预定的最大容量的消息,每条消息最多 160 个字符。支持以下操作,待测试:

  1. saveMessage: 在下一个空闲位置存储一条新的短信到收件箱。万一 消息正文超过160个字符,消息被拆分存储在多个 存储位置。
  2. deleteMessage:从收件箱中删除最早的(第一条)移动消息。
  3. listMessages:打印所有当前存储的消息的可读表示。将存储在多个部分中的消息连接在一起进行表示。

我需要对附加的这段代码进行一些单元测试。我不太熟悉 TestNG 和一般的单元测试,你能帮我举一些我可以做的测试示例吗?

mobile_storage\src\main\java\MobileMessage.java - https://pastebin.com/RxNcgnSi

/**
 * Represents a mobile text message.
 */
public class MobileMessage {
    //stores the content of this messages
    private final String text;

    //in case of multi-part-messages, stores the preceding message
    //is null in case of single message
    private MobileMessage predecessor;

    public MobileMessage(String text, MobileMessage predecessor) {
        this.text = text;
        this.predecessor = predecessor;
    }

    public String getText() {
        return text;
    }

    public MobileMessage getPredecessor() {
        return predecessor;
    }

    public void setPredecessor(MobileMessage predecessor) {
        this.predecessor = predecessor;
    }
}

mobile_storage\src\main\java\MobileStorage.java - https://pastebin.com/wuqKgvFD

import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.IntStream;

/**
 * Represents the message inbox of a mobile phone.
 * Each storage position in the inbox can store a message with 160 characters at most.
 * Messages are stored with increasing order (oldest first).
 */
public class MobileStorage {

    final static int MAX_MESSAGE_LENGTH = 160;

    private MobileMessage[] inbox;
    private int occupied = 0;

    /**
     * Creates a message inbox that can store {@code storageSize} mobile messages.
     * @throws IllegalArgumentException in case the passed {@code storageSize} is zero or less
     */
    public MobileStorage(int storageSize) {
        if(storageSize < 1) {
            throw new IllegalArgumentException("Storage size must be greater than 0");
        }

        this.inbox = new MobileMessage[storageSize];
    }

    /**
     * Stores a new text message to the inbox.
     * In case the message text is longer than {@code MAX_MESSAGE_LENGTH}, the message is splitted and stored on multiple storage positions.
     * @param message a non-empty message text
     * @throws IllegalArgumentException in case the given message is empty
     * @throws RuntimeException in case the available storage is too small for storing the complete message text
     */
    public void saveMessage(String message) {
        if(StringUtils.isBlank(message)) {
            throw new IllegalArgumentException("Message cannot be null or empty");
        }

        int requiredStorage = (int) Math.ceil((double) message.length() / MAX_MESSAGE_LENGTH);

        if(requiredStorage > inbox.length || (inbox.length - occupied) <= requiredStorage) {
            throw new RuntimeException("Storage Overflow");
        }

        MobileMessage predecessor = null;
        for(int i = 0; i < requiredStorage; i++) {
            int from = i * MAX_MESSAGE_LENGTH;
            int to = Math.min((i+1) * MAX_MESSAGE_LENGTH, message.length());

            String messagePart = message.substring(from, to);
            MobileMessage mobileMessage = new MobileMessage(messagePart, predecessor);
            inbox[occupied] = mobileMessage;
            occupied++;
            predecessor = mobileMessage;
        }
    }

    /**
     * Returns the number of currently stored mobile messages.
     */
    public int getOccupied() {
        return occupied;
    }

    /**
     * Removes the oldest (first) mobile message from the inbox.
     *
     * @return the deleted message
     * @throws RuntimeException in case there are currently no messages stored
     */
    public String deleteMessage() {
        if(occupied == 0) {
            throw new RuntimeException("There are no messages in the inbox");
        }

        MobileMessage first = inbox[0];

        IntStream.range(1, occupied).forEach(index -> inbox[index-1] = inbox[index]);
        inbox[occupied] = null;
        inbox[0].setPredecessor(null);
        occupied--;

        return first.getText();
    }

    /**
     * Returns a readable representation of all currently stored messages.
     * Messages that were stored in multiple parts are joined together for representation.
     * returns an empty String in case there are currently no messages stored
     */
    public String listMessages() {
        return Arrays.stream(inbox)
                .filter(Objects::nonNull)
                .collect(StringBuilder::new, MobileStorage::foldMessage, StringBuilder::append)
                .toString();
    }

    private static void foldMessage(StringBuilder builder, MobileMessage message) {
        if (message.getPredecessor() == null && builder.length() != 0) {
            builder.append('\n');
        }
        builder.append(message.getText());
    }
}

您将必须设置 testNG 。我使用 testNG 进行测试的方式是使用 Eclipse 和 maven(依赖管理)。一旦你有了它,你可以在 eclipse 的 maven-Java 项目下的 src 文件夹中的 test.java 文件中导入 classes。

您可能需要调整代码并为 testNG 导入必要的 classes。 Here is the official documentation of testNG and here 就是 assert class。

我尝试包含一些测试用例。希望这有帮助

您的 test.java 可能看起来像这样

        import yourPackage.MobileStorage;
        import yourPackage. MobileMessage;

        public class test{

        @BeforeTest
        public void  prepareInstance(){

            MobileStorage mobStg = new MobileStorage();
            MobileMessage mobMsg = new MobileMessage();
        }

        //test simple msg
        @Test
        public void  testSave(){

          mobStg.saveMessage("hello")
          assert.assertEquals("hello", mobMsg.getText())
        }

        //test msg with more chars
        @Test
        public void  testMsgMoreChar(){
             mobStg.saveMessage("messageWithMoreThan160Char")

             //access messagepart here somehow, i am not sure of that
              assert.assertEquals(mobMsg.getText(), mobStg.messagePart);

             //access message here somehow. This will test listMessages() and concatenation of msgs
             assert.assertEquals(mobStg.message, mobStg.listMessages())   
        }

 //test deletion of msg   
@Test    
public void  testDelete(){
             mobStg.deleteMessage();
              assert.assertEquals(null, mobMsg.getPredecessor()) 
        }



    }