spring—如何在java中使用mockito模拟局部变量

m4pnthwp  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(667)
class Testing{

 @Autowired
 ClassA classa; 

public void test(){
    MyService service = classa.someMethod();
service.getID(); //service is always null on this line
   }
}

ClassA {
public MyService someMethod(){
return Myservice.builder().id(1l).build();
}
}

import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
public class MyService {
    private Long id;
    private Long externalId;
}

试图模仿“myservice服务”,它总是空的。我们怎么嘲笑它?
myservice是一个builder类,@builder来自import lombok.builder;包裹

ds97pgxw

ds97pgxw1#

@ExtendWith(MockitoExtension.class)
class Testing{

    @Mock
    MyService service;

    public void test(){
        when(service.getID()).thenReturn(1);
        service.getID()
    }
}
pod7payv

pod7payv2#

使用junit4+mockito

@RunWith(MockitoJUnitRunner.class)
public class ClassATest {
    @Mock
    ClassA classa;

    @Test
    public void test(){
        //Arrange
        MyService service = MyService.builder().id(1l).build();
        when(classa.someMethod()).thenReturn(service);

        //Act
        MyService returnedService = classa.someMethod();

        //Assert
        assertEquals(1L, returnedService.getId().longValue());
    }
}

相关问题