【问题标题】:Unit tests with java [closed]使用java进行单元测试[关闭]
【发布时间】:2013-09-14 13:03:16
【问题描述】:

更新:

我有一个类似这样的代码:

class Sample 
{
    public boolean isALive(boolean isLive, int num) 
   {
       return isLive ? num == 3 : num == 2 || num == 3;
   } 
}

在测试中,会是这样的,

assertTrue(x.isAlive(true,1); 各种组合

即使不使用三元运算符,我也想以更简单的方式返回相同的结果。

有没有办法做到这一点?

解决方案: 返回数 == 3 || (isLive && 数字 == 2); //- 解决方案。

【问题讨论】:

  • “优化这个”是什么意思?不清楚您对什么感兴趣。另外,您应该指定您使用的 JUnit 版本,因为 JUnit 4 中的参数化测试可以帮助您。
  • 您的代码示例在语法上无效且不正确,您可能需要修复它。
  • 如果优化你的意思是让isAlive()更具可读性,那就去做吧!它不可读,因此无法理解。
  • Without even using the ternary operator , I want to return the same results, in more simple way. 是关于 JUnit 的问题!我不这么认为。
  • @JonSkeet Verison 我使用的是 JUnit4,有没有办法在不使用三元运算符的情况下做到这一点?

标签: java unit-testing junit4


【解决方案1】:

编程不是单行的。这是关于可读性。首先我会写一个测试:

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.runner.RunWith;
import com.googlecode.zohhak.api.TestWith;
import com.googlecode.zohhak.api.runners.ZohhakRunner;

@RunWith(ZohhakRunner.class)
public class SampleTest {

    Sample sample = new Sample();

    @TestWith({
        "true,  3,      true",
        "true,  2,      false",
        "false, 3,      true",
        "false, 2,      true",
        "false, 1,      false"
    })
    public void should_xxx(boolean isLive, int num, boolean expectedResult) {

        boolean actualResult = sample.isALive(isLive, num);         
        assertThat(actualResult).isEqualTo(expectedResult);
    }
}

然后我会写:

import static org.apache.commons.lang3.ArrayUtils.contains;

public class Sample {

    public boolean isALive(boolean isLive, int num) {

        int[] liveValues = {3};
        int[] deadValues = {2, 3};

        int[] validValues = isLive ? liveValues : deadValues;
        return contains(validValues, num);
    }
}

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2019-06-08
    • 2011-10-04
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    相关资源
    最近更新 更多