我正在尝试编写一个基本的 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());
}
}
我的 HelloWorldMessageService 实现代码
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());
}
}