How can I simulate an environment where BitConverter.IsLittleEndian is the opposite for my unit tests?

I use the two methods BitConverter.GetBytes and Array.Reverse to read and write binary data from a file due to judgment.

My unit tests pass, and the implementation seems fine.

How can I simulate an environment where BitConverter.IsLittleEndian is the opposite for my unit tests?

+6
source share
1 answer

To expand my comment: you need to use IoC (Inversion of Control) to inject the BitConverterEx instance where you need it. This class has a single โ€œparameterโ€: the end result of the byte[] output that it will read / write.

In the end, this problem is similar to the general โ€œhow can I make fun of DateTime.Now โ€ problem

In unit tests, instead of entering BitConverterEx you can enter ManipulableBitConverterEx , where you can control the processor flag. Or rather, you must unit test independently BitConverterEx and your classes so that when testing your classes you know that the results of BitConverterEx are correct.

 public class BitConverterEx { public bool ProcessorLittleEndian { get; protected set; } public bool DataLittleEndian { get; protected set; } public BitConverterEx(bool dataLittleEndian) { ProcessorLittleEndian = BitConverter.IsLittleEndian; DataLittleEndian = dataLittleEndian; } public byte[] GetBytes(int value) { byte[] bytes = BitConverter.GetBytes(value); if (DataLittleEndian != ProcessorLittleEndian) { Array.Reverse(bytes); } return bytes; } public int ToInt32(byte[] value, int startIndex) { if (DataLittleEndian == ProcessorLittleEndian) { return BitConverter.ToInt32(value, startIndex); } byte[] value2 = new byte[sizeof(int)]; Array.Copy(value, startIndex, value2, 0, value2.Length); Array.Reverse(value2); return BitConverter.ToInt32(value2, 0); } } public class ManipulableBitConverterEx : BitConverterEx { public ManipulableBitConverterEx(bool processorLittleEndian, bool dataLittleEndian) : base(dataLittleEndian) { ProcessorLittleEndian = processorLittleEndian; } } 

Note that if you need to reuse this class, Array.Reverse can be "slow." There are solutions to invert the contentability of data types that control single bytes with shift, or, xor, ...

+2
source

Source: https://habr.com/ru/post/986961/


All Articles