我有一个Java命令行程序.我想创建JUnit测试用例以便能够模拟System.in.因为当我的程序运行时,它将进入while循环并等待来自用户的输入.我如何在JUnit中模拟它?
谢谢
我正在使用JUnit编写集成测试来自动测试基于控制台的应用程序.该应用程序是家庭作业,但这部分不是作业.我希望自动化这些测试以提高工作效率 - 我不想再返回并重新测试已经测试过的应用程序部分.(使用单元测试的标准原因)
无论如何,我无法弄清楚或找到关于捕获输出的文章,以便我可以对其进行assertEquals操作,也不提供自动输入.我不在乎输出/输入是否进入控制台/输出窗格.我只需要执行测试并验证输出是否是给定输入的预期.
任何人都有一篇文章或代码来帮助解决这个问题.
我知道强烈建议在与文件系统分离时运行单元测试,因为如果你在测试中触摸文件系统,你也可以测试文件系统本身.好的,这是合理的.
我的问题是,如果我想测试文件保存到磁盘,我该怎么办?与数据库一样,我将一个负责数据库访问的接口分开,然后为我的测试创建另一个实现?或者可能还有其他方式?
我写了一个类,它从main方法中获取控制台和参数的输入.main方法为不同的控制台输入调用不同的方法,并为不同的参数调用不同的函数.所以我想通过模拟文件中的这些输入来使用Junit测试这个主要方法.我该怎么做?在junit中是否有任何特殊规定来测试班级的主要方法?
我在项目中第一次使用log4j.一位程序员告诉我,使用System.out.println被认为是一种糟糕的风格,log4j就像现在的日志记录标准一样.
我们做了很多JUnit测试 - System.out结果证明更难测试.
因此我开始将log4j用于Console控制器类,这只是处理命令行参数.
// log4j logger config
org.apache.log4j.BasicConfigurator.configure();
Logger logger = LoggerFactory.getLogger(Console.class);
Category cat = Category.getRoot();
Run Code Online (Sandbox Code Playgroud)
似乎工作:
logger.debug("String");
Run Code Online (Sandbox Code Playgroud)
生产:
1 [main] DEBUG project.prototype.controller.Console - String
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
运行时:
public static void main(String... args) throws InterruptedException {
while (true) {
System.out.print(".");
Thread.sleep(200);
}
}
Run Code Online (Sandbox Code Playgroud)
从junit运行相同的代码时:
@Test
public void test() throws Exception {
while (true) {
System.out.print(".");
Thread.sleep(200);
}
}
Run Code Online (Sandbox Code Playgroud)
有不同的行为:
对于main() - 输出按预期显示,因为进程运行("." - >".." - >"...")
但是,对于JUnit,当运行相同的代码时,进程运行时不显示输出 - 仅在退出测试时刷新.
为什么会这样?如果我需要在测试运行期间在控制台中显示状态,有没有办法解决它?
我需要打印到同一行,所以使用println不适合.
在React Native AppState库中:
iOS有三种状态background-> inactive-> active
Android只有background-> active
当Android应用完全落后时,MainActivity来自onPause - > onStop
当有系统通知时,例如In app购买,它会进入onPause
当应用程序从后台转到前台onStop - > onResume时,我需要运行一些代码
如果由于系统通知onPause - > onResume而短暂暂停应用程序,我不希望它运行
这可能吗?React的生命周期事件没有onHostStop
我尝试从MainActivity为每个Activity生命周期事件发出一个事件,但这导致App崩溃并出现空指针异常.
甚至可以从MainActivity向React Native发出事件吗?
谢谢
编辑添加了代码以显示从MainActivity发出事件的尝试
MainActivity.java片段
import com.facebook.react.ReactActivity;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class MainActivity extends ReactActivity {
DeviceEventManagerModule.RCTDeviceEventEmitter eventEmitter;
@Override
public void onStop() {
super.onStop();
eventEmitter.emit("onStop", "ActivityonStop");
}
}
Run Code Online (Sandbox Code Playgroud)
反应原生
const nativeEventListener = DeviceEventEmitter.addListener('onStop',
(e)=>{
console.log("NATIVE_EVENT");
dispatch({type: "NATIVE_EVENT"})
})
Run Code Online (Sandbox Code Playgroud)
logcat中的错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.realer.android, PID: 15251
java.lang.RuntimeException: …Run Code Online (Sandbox Code Playgroud) 如何为非法反射访问警告抛出异常?例如,考虑以下代码:
import org.apache.commons.lang3.builder.*;
class Test {
public static void main(String[] args) {
System.out.println(ReflectionToStringBuilder.toString(Boolean.TRUE));
}
}
Run Code Online (Sandbox Code Playgroud)
此代码向 System.err 打印以下警告:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.commons.lang3.builder.ReflectionToStringBuilder (file:/Users/brianschack/eclipse-workspace/User%20Libraries/com
mons-lang3-3.7/commons-lang3-3.7.jar) to field java.lang.Boolean.value
WARNING: Please consider reporting this to the maintainers of org.apache.commons.lang3.builder.ReflectionToStringBuilder
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Run Code Online (Sandbox Code Playgroud)
Boolean.TRUE 是一个如此简单的值,我真的不需要 ReflectionToStringBuilder。但是更复杂的类型(例如 HashMap)会打印相同的警告。我选择 Boolean.TRUE 是为了简化这个例子。
当我搜索此警告消息时,我发现建议将其报告给包维护者、避免警告或完全禁用它(JDK9:发生非法反射访问操作。org.python.core.PySystemState)。 …
java reflection illegalaccessexception apache-commons-lang apache-commons-lang3
我正在使用一些System.out.print本身有一些命令的遗留代码.我的eCobertura插件显示这条线为红色,所以我想对它们进行单元测试.
这里的计算器,我发现了一种单元测试控制台输出这是我的东西是很有趣的.
我是这样做的:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void cleanUpStreams() {
System.setOut(null);
}
@Test
public void out() {
System.out.print("Some message from the system");
assertEquals("Some message from the system", outContent.toString());
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,测试变得很好,但是当我再次运行代码覆盖率插件时,我收到以下消息:
网络"Thread-0"中的异常java.lang.NullPointerException net.sourceforge.cobertura.coveragedata.TouchCollector.applyTouchesOnProjectData(TouchCollector.java:186)at net.sourceforge.cobertura.coveragedata.ProjectData.saveGlobalProjectData(ProjectData.java:267) )at java.slang.Thread.run(Thread.java:662)的net.sourceforge.cobertura.coveragedata.SaveTimer.run(SaveTimer.java:31)
我有些疑惑:
System.out.print()'s?我编写了一个将输出打印到控制台的方法.我该怎么测试呢?
public class PrinterForConsole implements Printer<Item>{
public void printResult(List<Item> items) {
for (Item item: items){
System.out.println("Name: " + item.getName());
System.out.println("Number: " + item.getNumber());
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前,我的测试看起来像这样
public class TestPrinter{
@Test
public void printResultTest() throws Exception {
(am figuring out what to put here)
}
}
Run Code Online (Sandbox Code Playgroud)
我已经在这篇文章中阅读了解决方案(感谢@Codebender和@KDM突出显示这一点)但不太明白.那里的解决方案如何测试print(List items)方法?因此,在这里重新询问.
我在春季曾进行过junit测试集成测试和控制器测试,通常我们会测试方法的输出,但是当我尝试在main方法中测试一个简单的hello世界时,我不知道如何进行操作,因此希望获得任何方法关于写什么的想法
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
Run Code Online (Sandbox Code Playgroud)
这是简单的Java类,我知道如何测试它,我试图写这样的东西
public void mainMethodTest() throws Exception{
System.out.println("hello world");
String[] args = null;
Assert.assertEquals(System.out.println("hello world"),App.main(args));
}
Run Code Online (Sandbox Code Playgroud) 我正在编写测试,我想通过测试方法捕获STDOUT上发送的消息.这是我的代码:
@Test
public void testAction() throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
CmdLineException, IOException {
PrintStream originalSTDOUT = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
try {
System.setOut(ps);
// Call to the method that will print text to STDOUT...
ps.flush();
String batchLog = baos.toString("UTF-8");
assertTrue("Invalid exception text !", batchLog.contains("my expected text..."));
} finally {
System.setOut(originalSTDOUT);//Restore original STDOUT
originalSTDOUT.write(baos.toByteArray());// Write back to STDOUT, even if I comment this line, outputs go to STDOUT...
ps.close();
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,batchLog虽然我仍然可以读到STDOUT的预期文本,但它总是空的. …
我班上有几种方法
public class StringChecking
{
public static void main(String[] args);
public void stringChecker(String text, int number); //takes a string and prints that out.
}
Run Code Online (Sandbox Code Playgroud)
我想编写单元测试来测试' stringChecker()'方法.我想知道我会怎么做.当我StringChecking在JUnit Testing类中创建一个类型的对象时,我似乎无法stringChecker()从该实例访问方法.
StringChecker方法根据参数打印出传入文本的特定数量的单词.我希望检查打印出的前10个单词是否与预期结果相同.
JUnit测试类
String expected = "My name is";
asserEquals(expected, actual);
Run Code Online (Sandbox Code Playgroud)
我猜我会让我的stringChecker方法返回一些东西,以便进行检查.但我不明白为什么我无法从测试类访问该方法.
java ×11
junit ×9
unit-testing ×3
junit4 ×2
tdd ×2
android ×1
cobertura ×1
command-line ×1
io ×1
legacy ×1
logfiles ×1
logging ×1
react-native ×1
redirect ×1
reflection ×1
stdout ×1
system.out ×1
testing ×1
timestamp ×1