如何进行Junit测试

时间:2018-07-09 18:44:34

标签: java

如何为此代码编写Junit测试;

public String getDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");

        Date date = new Date();

    return dateFormat.format(date)

2 个答案:

答案 0 :(得分:0)

如果添加允许传递日期的方法,则测试起来会容易得多:

public String getDate(Date date) {
    return (date != null) ? new SimpleDateFormat("MM/dd/yyyy").format(date) : "";
}

public String getDate() {
    return this.getDate(new Date());
}

让您的JUnit测试通过一个固定的日期,以便您可以重复并知道它:

@Test
public void testGetDate() {
    // setup
    String expected = "07/09/2018";
    Date testDate = new SimpleDateFormat("MM/dd/yyyy").parse(expected);
    // exercise
    // Name of the class that you put the getDate() method into.   
    YourClass yc = new YourClass();
    String actual = yc.getDate(testDate);
    // assert
    Assert.assertThat(expected, actual);
}

答案 1 :(得分:0)

编写测试非常简单,容易,尽管您可以看到测试和被测方法有很多重复。我建议重新编写您的测试方法。

@Test
public void test() {
    //arrange
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");

    //act
    String actual = getDate();

    //assert
    assertEquals(dateFormat.format(date), actual);
}

public String getDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");

    Date date = new Date();

    return dateFormat.format(date);
}
相关问题