简体   繁体   English

如何使用Mockito在另一个Mock类中模拟Spring Message Resource?

[英]How to mock Spring Message Resource inside another Mock class with Mockito?

In my test when I assert de exception message I'm getting null 在我的测试中,当我断言异常消息时,我得到的是null

I'm not getting mock the message inside Service.... :( 我没有嘲笑Service .... :(

I have: 我有:

My test: 我的测试:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest {

    @InjectMocks
    private ServiceImpl service;

    @Mock
    private Message message;

    public static final String REQUIRED_FIELD = "required.field";

    @Before
    public void setUp() {
        when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD);

        System.out.println(message.getMessage(REQUIRED_FIELD, new ArrayList()));
    }

    @Test(expected = MyException.class)
    public void testCancel_shouldValidCancellation_and_ThrowTicketException_with_RequiredFieldMessage() {
        try {
            Object object = //... new object
            service.do(object);
        } catch (Exception e) {
            assertEquals(REQUIRED_FIELD, e.getMessage()); // <-- e.getMessage return null!!!
        }
    }
}

My service: 我的服务:

@Service
public class ServiceImpl implements Service {

    @Autowired
    Message message;

    @Override
    public Object do(Object object) {
        if(object.getSomeAttribute() == null)) {
            throw new MyException(message.getMessage("required.field", "attribute"));
        }

        //doSomething...
        return something;
    }
}

In the setUp() of test the printLn() prints required.field but I can't use message of Service !! 在测试的setUp()中, printLn()打印出required.field但是我不能使用Service message

Can someone help me? 有人能帮我吗?

It is hard tell for sure, without knowledge about the interface of Message , but it is easy to spot that you configure mock object to stub method with signature getMessage(String, List) : 很难确定,没有Message的接口知识,但是很容易发现您使用签名getMessage(String, List)将模拟对象配置为存根方法:

when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD);

However, ServiceImpl uses getMessage(String, String) . 但是, ServiceImpl使用getMessage(String, String) The default value which is returned by mock in this case is null . 在这种情况下,模拟返回的默认值为null You have to configure mock object properly. 您必须正确配置模拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM