2016-04-11 133 views
-4

如何为以下方法编写JUnit测试?Java的JUnit测试

private static final String CHAR_LIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 

    private int getRandNum() { 
     Random getRand = new Random(); 
     int randomNum = getRand.nextInt(CHAR_LIST.length()); 
     if (randomNum == 0) { 
       return randomNum; 
     } else { 
       return randomNum - 1; 
     } 
    } 
+0

你想测试一下呢? –

+1

'randomNum - 1 == -1'与'randomNum == 0'相同。 –

+0

运行一百次,检查结果是从未得到0 – Stultuske

回答

0

这是很难在这里建立100%的有意义的测试,但我认为你应该分解你的方法一点点,所以你可以嘲笑Random对象。

但首先,你应该简化你的方法。如果我理解正确,那么你需要为列表生成一个随机索引,但是你这样做的方式永远不会生成列表中的最后一个索引,并且获得第一个索引(0)的可能性是两次获得其他任何指数。

//either this: 
private Random random = new Random(); 
//or this: 
Random createRandom() { 
    return new Random(); 
} 

private int getRandNum() { 
    //either this: 
    return random.nextInt(CHAR_LIST.size()); 
    //or this: 
    return createRandom().nextInt(CHAR_LIST.size()); 
} 

然后,您可以用模拟/间谍更换随机对象,无论是通过反射,或通过间谍活动:

public class MyClassTest { 
    private MyClass myClass; 
    private Random mockedRandom; 

    @Before 
    public void setup() { 
     myClass = spy(new MyClass()); 
     mockedRandom = mock(Random.class); 
     when(myClass.createRandom()).thenReturn(mockedRandom); 
    } 

    @Test 
    public void getRandNumShouldGenerateAValidIndexForCHAR_LIST() { 
     //Given CHAR_LIST.size() = 5 
     when(mockedRandom.nextInt(5)).thenReturn(2); 

     final int randomNumber = myClass.getRandNum(); 

     assertEquals(2, randomNumber); 
     verify(mockedRandom).nextInt(5); 
    } 

    //a "black box" approach: 
    @Test 
    public void blackboxish() { 
     //Make sure CHAR_LIST.size() = 3 
     when(myClass.createRandom()).thenReturn(new Random()); 
     for (int i = 0; i < 100; i++) { 
      final int random = myClass.getRandNum(); 
      assertTrue(random >= 0); 
      assertTrue(random < 3); 
     } 
    } //there is a theoritical possibility of a false positive here, but it's small.. 
+0

什么是MyClass,模拟,何时验证?我得到这些错误 – lol

+0

MyClass是你的班级的名字。 mock/when/verify是Mockito方法,Mockito(或其他一些模拟框架)对于进行单元测试非常有用。 – Tobb