在我的测试中,当我断言异常消息时,我得到了null
我没有在服务中嘲笑消息...... :(
我有:
我的测试:
@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!!!
}
}
}
我的服务:
@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;
}
}
在setUp()
测试中,printLn()
打印required.field
,但我无法使用message
的{{1}} !!
有人可以帮助我吗?
答案 0 :(得分:1)
如果不知道Message
的界面,很难确定,但很容易发现您使用签名getMessage(String, List)
将模拟对象配置为存根方法:
when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD);
但是,ServiceImpl
使用getMessage(String, String)
。在这种情况下,mock返回的默认值是null
。您必须正确配置模拟对象。