gpt4 book ai didi

spring - 尝试使用JavaConfig在Spring中编写junit测试

转载 作者:行者123 更新时间:2023-12-04 13:33:03 25 4
gpt4 key购买 nike

我正在尝试为示例项目编写一个junit测试,但是不知道如何在jUnit测试中访问ApplicationContext:

这是工程的主要类别:

public static void main(String[] args)
{
// in this setup, both the main(String[]) method and the JUnit method both specify that
ApplicationContext context = new AnnotationConfigApplicationContext( HelloWorldConfiguration.class );
MessageService mService = context.getBean(MessageService.class);
HelloWorld helloWorld = context.getBean(HelloWorld.class);

/**
* Displaying default messgae
*/
LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());

/**
* Saving Message to database
*/
Message message = new Message();
message.setMessage(helloWorld.getMessage());
mService.SaveMessage(message);

/**
* Settting new message in bean
*/
helloWorld.setMessage("I am in Staten Island, New York");
LOGGER.debug("Message from HelloWorld Bean: " + helloWorld.getMessage());

/**
* Saving Message in database.
*/
message.setMessage(helloWorld.getMessage());
mService.SaveMessage(message);

/**
* Getting messages from database
* - display number of message(s)
* - display each message in database
*/
List<Message> myList = mService.listMessages();
LOGGER.debug("You Have " + myList.size() + " Message(s) In The Database");

for (Message i : myList)
{
LOGGER.debug("Message: ID: " + i.getId() + ", Message: " + i.getMessage() + ".");
}
}

现在是junit测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HelloWorldConfiguration.class)
public class TestApp {


@Test
public void testBean() {
HelloWorld helloWorld = context.getBean(HelloWorld.class);

helloWorld.setMessage("I Love Dogs");
Assert.assertEquals(helloWorld.getMessage(), "I Love Dogs");
}
}

最佳答案

您可以使用 Autowiring 。注意,大多数时候,您对应用程序上下文本身不感兴趣,而对与之关联的一个或多个bean感兴趣。以下是两个实质上执行相同操作的示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HelloWorldConfiguration.class)
public class TestApp {

@Autowired
HelloWorld helloWorld;

@Test
public void testBean() {
helloWorld.setMessage(...);
// asserts, etc.
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HelloWorldConfiguration.class)
public class TestApp {

@Autowired
ApplicationContext applicationContext;

HelloWorld helloWorld;

@Before
public void setUp() {
helloWorld = context.getBean(HelloWorld.class);
}

@Test
public void testBean() {
helloWorld.setMessage(...);
// asserts, etc.
}
}

有关详细信息,请参见 reference docs

关于spring - 尝试使用JavaConfig在Spring中编写junit测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16299988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com