Mockito+JUnit实现单元测试

这种组合方式,可以理解为仅依赖的是JUnit和Mockito,spring没写是因为关键注解的使用,并没有用到@Resource、@ComponentScan等,

 

1、首先导入包


    
    ...
    
        junit
        junit
        4.12
        test
    
    
        org.mockito
        mockito-all
        1.10.19
        test
    
    
        org.mockito
        mockito-all
        1.10.19
        test
    

2、被测试类production-class:

@Service
public class MySomeServiceImpl implements SomeService {
    @Resource
    private ServiceA serviceA;
    @Resource
    private ServiceB serviceB;
    @Value("${server.port}")
    private int port;
  
    public String sayHello(){
      String result=null;
      List list=serviceA.getText("zhangsan",12);
      // do...
      result=list.get(0);
      return result;
    }
}

3、单元测试-执行类:(省掉了配置项)

@RunWith(MockitoJUnitRunner.class)
public class MySomeServiceImplTest {
    
    @InjectMocks
    private MySomeServiceImpl mySomeService;
    @Mock
    public ServiceA serviceA;
    
    @Before
    public void setUp(){
        // 手动注入@Value字段
        ReflectionTestUtils.setField(serviceA,"port",1234);
    }
    @Test
    public void sayHelloTest() {
        Mockito.when(serviceA.getText(Mockito.any(String.class))).thenReturn("AAA");
        
        String result = mySomeService.sayHello();
        Assert.assertEquals("执行失败", pickZoneNos, "AAA");
    }
}

这种方式更加优雅,减少了无效的Bean定义,而且利用反射对于@Value的字段进行注入。

 

你可能感兴趣的:(测试,单元测试,java)