Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 将uint32数组写入一个字节片并获取它_Unit Testing_Go_Binary_Byte - Fatal编程技术网

Unit testing 将uint32数组写入一个字节片并获取它

Unit testing 将uint32数组写入一个字节片并获取它,unit-testing,go,binary,byte,Unit Testing,Go,Binary,Byte,我正在尝试为os.File或更具体的io.Reader创建一个模拟。我想模拟128位具体数据的读取,而不进行实际读取 使用单个uint32,没有问题 模拟: 试验方法(简化): 但是,当我需要模拟读取uint32slice时,PutUint32没有帮助,因为它从一开始就写入slice(覆盖了以前写入的数据)。我尝试了一系列字节和二进制工具的组合,但每次我无法从字节中获取数据时都没有运气。这是我最后一次尝试(不是唯一的尝试): 使用与上述相同的测试方法,我获得了一个空切片[0,0,0,0]请注意,

我正在尝试为
os.File
或更具体的
io.Reader
创建一个模拟。我想模拟128位具体数据的读取,而不进行实际读取

使用单个
uint32
,没有问题

模拟:

试验方法(简化):

但是,当我需要模拟读取
uint32
slice时,
PutUint32
没有帮助,因为它从一开始就写入slice(覆盖了以前写入的数据)。我尝试了一系列
字节
二进制
工具的组合,但每次我无法从字节中获取数据时都没有运气。这是我最后一次尝试(不是唯一的尝试):

使用与上述相同的测试方法,我获得了一个空切片
[0,0,0,0]
请注意,这是一个模拟的
os.File.Read
方法,因此我无法创建一个新的字节片来代替它,我需要将数据写入现有的字节片。

首先我想知道如何解决这个问题。我还想知道为什么只有
[0,0,0,0]


感谢您的回答

切片共享一个底层数组,您可以将(PutUint32)写入buf[4:],buf[8:]等。

切片共享一个底层数组,您是否尝试过写入buf[2:],buf[4:]等?@frankjeannin,我尝试了很多事情。。。“我现在就试试看。”弗兰克杰宁,你说得对!我发现了我的错误。我认为应该传递关于位而不是字节的索引,所以
buf[32://code>not
buf[4://code>。非常感谢。请把你的评论作为回答,我会接受的;)
func (f *FileMock) Read(buf []byte) (n int, err error) {
    binary.BigEndian.PutUint32(buf, uint32(2052))
    return len(buf), nil
}       
b := make([]byte, 128)                                                      
meta_data := make([]uint32, 4)                                                                                                                                 
_, err = s.Read(b)                                                                          
if err != nil {                                                                             
    // Handle error         
}                                                                                                                                                                                       
binary.Read(bytes.NewBuffer(b), binary.BigEndian, &meta_data)                                                                                                                               
log.Print(meta_data) // Output [2052 0 0 0]
func (f *FileMock) Read(b []byte) (n int, err error) {
    buf := bytes.NewBuffer(make([]byte, len(b)))
    err = binary.Write(buf, binary.BigEndian, [4]uint32{2051, 123, 28, 28})
    buf.Read(b)
    return len(b), nil
}