我正在尝试编写一个基本的JUnit教程,我正在使用一个基本服务层的简单Hello World示例来演示这一点。我的问题是,即使测试输出与我的控制数据匹配,assertEquals仍然返回false。你能解释一下为什么assertEquals不起作用,并说明我如何解决这个问题?
JUnit错误
org.junit.ComparisonFailure: expected:<Hello World[]> but was:<Hello World[
]>
我的代码测试样本
package com.springtutorial.mavenhelloworld.service;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import com.springtutorial.junitandmavenhelloworld.service.HelloWorldMessage;
import com.springtutorial.junitandmavenhelloworld.service.HelloWorldMessageImplementation;
import com.springtutorial.junitandmavenhelloworld.service.HelloWorldMessageService;
import com.springtutorial.junitandmavenhelloworld.service.HelloWorldMessageServiceImplementation;
public class HelloWorldMessageServiceImplementationTest
{
static String controlMessageContent;
static HelloWorldMessage controlMessage;
HelloWorldMessage testMessage;
HelloWorldMessageService testMessageService;
@Rule
public final StandardOutputStreamLog testLog = new StandardOutputStreamLog();
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
controlMessageContent = new String("Hello World");
controlMessage = new HelloWorldMessageImplementation(controlMessageContent);
}
@Before
public void setUp() throws Exception
{
testMessage = new HelloWorldMessageImplementation("Hello World");
testMessageService = new HelloWorldMessageServiceImplementation(testMessage);
}
@Test
public void testGetMessage()
{
assertEquals(testMessage, testMessageService.getMessage());
}
@Test
public void testSetMessage()
{
testMessageService.setMessage(new HelloWorldMessageImplementation("Test Message"));
assertEquals("Test Message", testMessageService.getMessage().getMessageAsString());
}
@Test
public void testPrintMessageToConsole()
{
testMessageService.printMessageToConsole();
assertEquals(controlMessageContent, testLog.getLog());
}
}
我的HelloWorldMessageServiceImplementation代码
package com.springtutorial.junitandmavenhelloworld.service;
public class HelloWorldMessageServiceImplementation implements
HelloWorldMessageService
{
HelloWorldMessage message;
public HelloWorldMessageServiceImplementation(HelloWorldMessage newMessage)
{
super();
this.setMessage(newMessage);
}
public HelloWorldMessage getMessage()
{
return this.message;
}
public void setMessage(HelloWorldMessage newMessage)
{
this.message = newMessage;
}
public void printMessageToConsole()
{
System.out.println(this.message.getMessageAsString());
}
}
答案 0 :(得分:0)
问题是在println()
课程中使用HelloWorldMessageServiceImplemenation
。此函数将回车符\n
添加到字符串的末尾,导致输出与控制数据不匹配。将此更改为print()
方法,或将回车符添加到测试字符串的末尾。
将回车添加到测试控制数据的正确方法如下
controlMessageContent = new String("Hello World\n");