java如何校验uuid,如何对使用Java UUID的代码进行单元测试?

I have a piece of code which is expected to populated one attribute of response object with Java UUID (UUID.randomUUID()).

How can I unit test this code from outside to check this behaviour? I don't know the UUID that would be generated inside it.

Sample code which needs to be tested:

// To test whether x attribute was set using an UUID

// instead of hardcode value in the response

class A {

String x;

String y;

}

// Method to test

public A doSomething() {

// Does something

A a = new A();

a.setX( UUID.randomUUID());

return a;

}

解决方案

Powermock and static mocking is the way forward. You will need something like:

...

import static org.junit.Assert.assertEquals;

import static org.powermock.api.mockito.PowerMockito.mockStatic;

...

@PrepareForTest({ UUID.class })

@RunWith(PowerMockRunner.class)

public class ATest

{

...

//at some point in your test case you need to create a static mock

mockStatic(UUID.class);

when(UUID.randomUUID()).thenReturn("your-UUID");

...

}

Note the static mock can be implemented in a method annotated with @Before so it can be re-used in all test cases that require UUID in order to avoid code repetition.

Once the static mock is initialised, the value of UUID can be asserted somewhere in your test method as follows:

A a = doSomething();

assertEquals("your-UUID", a.getX());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值