‘TextFromStandardInputStream’ class is used to create tests that depends on System input (System.in).
'provideLines' method is used to provide input to the program.
Arithmetic.java
package com.sample.app;
import java.util.Scanner;
public class Arithmetic {
public int sum() {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
return a + b;
}
}
As you see sum() method, it takes two integers a and b, return sum of a and b.
We can pass input 1, 2 using provideLines method like below.
@Rule
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
systemInMock.provideLines("1", "2");
ArithmeticTest.java
package com.sample.app.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
import com.sample.app.Arithmetic;
public class ArithmeticTest {
@Rule
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
private Arithmetic arithemtic = new Arithmetic();
@Test
public void sumOf1And2() {
systemInMock.provideLines("1", "2");
assertEquals(3, arithemtic.sum());
}
}
You can download complete working application from this link.
https://github.com/harikrishna553/system-rules
Previous Next Home
No comments:
Post a Comment