0
我正在嘗試編寫一個基本的JUnit教程,我用一個簡單的Hello World示例演示瞭如何使用基本服務層。我的問題是,即使測試輸出符合我的控制數據,assertEquals仍然返回false。你能解釋爲什麼assertEquals不工作,並說明我該如何解決這個問題?在JUnit中聲明正確的控制檯輸出
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());
}
}