junit模拟不为依赖类创建对象

时间:2018-10-04 08:34:45

标签: spring-boot junit mocking

当我尝试运行junit test时,该对象没有打印出MessageValidation类,并且没有将其命名为messageValidation。

    @Controller
    public class ReceiverController{
    @Autowired
    MessageValidation messageValidation;
    public void receiveMsg(@RequestBody String message){
    messageValid(message);
    }
    private messageValid(String message){
    system.out.println("messageValidation object is " + messageValidation)
    //here displaying name only not getting object
    messageValidation.verfication(message);
    }
    }

 MessageValidation class

    @Service
    public class MessageValidation{

    public String verification(String message){
    //stuff
    return "something";
    }
    }

我想为MessageValidation创建依赖对象

    @SpringBootTest
    @RunWith(MockitoJUnitRunner.class)
    @SpringBootConfiguration

    public class ReceiverControllerTest(){
    @InjectMocks
    ReceiverController receive;
    @Mock
    MessageValidation messageValidation;

    @Before
    public void setup() {
    MockitoAnnotations.initMocks(this);
    }

    @Test
    public void ReceiveMsgTest(){
    String msgTest="something";
    Mockito.when(messageValidation.verification("test")).thenReturn(msgTest);
    receive.receiveMsg("msg");
    }
}

0 个答案:

没有答案