有人可以告诉我如何为mockito
编写ServletInitializer
测试吗?
package com.home.service.project.HomeServiceProject;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(HomeServiceProjectApplication.class);
}
}
最佳答案
您可以编写以下单元测试,以确保使用正确的源类调用SpringApplicationBuilder
,并且该方法返回传递给configure
的相同实例。
@ExtendWith(MockitoExtension.class)
//@RunWith(MockitoJUnitRunner.class) for JUnit 4
class ServletInitializerTest {
@Mock
private SpringApplicationBuilder springApplicationBuilder;
@Test
public void testIt() {
ServletInitializer servletInitializer = new ServletInitializer();
when(springApplicationBuilder.sources(HomeServiceProjectApplication.class)).thenReturn(springApplicationBuilder);
SpringApplicationBuilder result = servletInitializer.configure(springApplicationBuilder);
verify(springApplicationBuilder).sources(HomeServiceProjectApplication.class);
assertEquals(springApplicationBuilder,result);
}
}
我仍然会质疑该单元测试的价值,而是尝试找到一种编写集成测试的方法,以至少一次启动整个应用程序,以查看所有功能是否正常运行。