如何对使用Java UUID的代码进行单元测试? [英] How do I unit test code which uses Java UUID?

查看:157
本文介绍了如何对使用Java UUID的代码进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,预计会用Java UUID( UUID.randomUUID())填充响应对象的一个​​属性。

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

如何从外部对此代码进行单元测试以检查此行为?我不知道将在其中生成的UUID。

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.

需要测试的示例代码:

// 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和静态模拟是前进的方向。你需要这样的东西:

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");
    ...
    }

注意静态模拟可以在一个实现使用@Before注释的方法,因此它可以在需要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.

初始化静态模拟后,值可以在测试方法的某个地方声明UUID,如下所示:

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());

这篇关于如何对使用Java UUID的代码进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆