1. 程式人生 > 其它 >單元/整合測試 junit/testsng

單元/整合測試 junit/testsng

1、使用junit測試

@RunWith(MockitoJUnitRunner.class) // 使用註解或者initMocks 注入mock public class TestJunit { @Mock TestDao testDao; @InjectMocks TestService testService; /* @Before public void initMock(){ MockitoAnnotations.initMocks(this); }*/ @Test public void test1() { when(testDao.Insert()).thenReturn(
"test"); String s = testService.insert(); System.out.println(s); } }


2、使用junit整合springboot測試
@SpringBootTest(classes = Springapplication22.class)    //springboot啟動類,依靠啟動類找掃描springcontext的bean
@RunWith(SpringRunner.class)
public class testJunitIntegration {

@Autowired
ApplicationContext context;

@MockBean //從容器找到bean,並且把mockbean替換舊的bean
TestDao testDao;

@Autowired
TestService te;


@Test
public void test1() {
// TestService testService1 = (TestService)context.getBean(TestService.class);
when(testDao.Insert()).thenReturn("test");
// String insert = testService1.insert();

String s = te.insert();
System.out.println(s);
}

}
3、使用Testng整合springboot測試
@SpringBootTest(classes = Springapplication22.class)
//@ContextConfiguration
public class testngt2 extends AbstractTestNGSpringContextTests{

@Autowired
ApplicationContext context;

@MockBean
@Autowired //先從容器裡取得bean,再mockbean替換
TestDao testDao;

@Autowired
TestService testService;



@Test
public void test1() {
// TestService testService1 = (TestService)context.getBean(TestService.class);
when(testDao.Insert()).thenReturn("test");

String insert1 = testService.insert();
System.out.println(insert1);

}

}